Search code examples
htmlcssreactjsjsxchakra-ui

Can't click button inside a clickable div


I am using Chakra UI in react, When I am trying to click a Button inside a clickable Box, The function of Box is being executed. Z-index also not fixing the issue.

My code:

<Box
   w="90%"
   h="auto"
   mt="10px"
   position="relative"
   key={index}
   borderWidth="1px"
   borderRadius="lg"
   onClick={() =>
   history.push(`/products/${item.cat_name}/${item.id}`)}
>
 <h1 className={styles.heading_bold}>{item.cat_name}</h1>
<Button position="absolute" top="3" right="3" zIndex="0"> //Button not able to click
 Options
</Button
</Box>

Codesandbox link


Solution

  • It should be onClick not onclick.

       <Button
            onClick={() => console.log("button clicked")} // Typo fixed
            position="absolute"
            top="3"
            right="3"
            zIndex="0"
          >
    

    Here is the CodeSandbox: https://codesandbox.io/s/debuuge-lwio5

    Also note that Button is inside the Box so first Button handler gets invoked and then also the Box handler once button is clicked.

    To stop event from propagating you can use the following code.

      <Button
            onClick={(e) => {
              e.stopPropagation();
              console.log("button clicked");
            }}
            position="absolute"
            top="3"
            right="3"
            zIndex="0"
          >
    

    Now whenever you click on Button only it's handler will get invoked and you will see, button clicked in the output.