Search code examples
javascripthtmlreactjsonclickstyled-components

how to not set off onclick in some parts of div?


I want to set off an onclick when you click the outside of a div but not the div. how can I make it that the onclick function is not set off when clicked in the specific div?

    import React from "react"
    import { Container, Backdrop, Card } from "./styles"

    export default function FocusSneakerCard(props){
        function click(){
            props.setModal(false)
            props.setData({})
        }

        return(
            <Container>
                <Backdrop onClick={() => click()}>
                    <Card>
                        
                    </Card>
                </Backdrop>
            </Container>
        )
    }

PS I'm using styled-components.


Solution

  • I found something called event.stopPropagation() which "prevents further propagation of the current event in the capturing and bubbling phases". You can include event.stopPropagation in an onClick event of the child element like so:

      const parentClick = () => {
        alert("clicked");
      };
    
      const childClick = (e) => {
        e.stopPropagation();
      };
    
      return (
        <div className="outer" onClick={parentClick}>
          <div className="inner" onClick={childClick}>
            Cant Click
          </div>
        </div>
      );
    }
    

    https://codesandbox.io/s/laughing-dubinsky-zw013?file=/src/App.js:101-382

    Note: "It does not, however, prevent any default behaviors from occurring; for instance, clicks on links are still processed. If you want to stop those behaviors, see the preventDefault() method." from MDN