Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - onClick function not working inside a flexbox

When I click the search button in the flexbox, I expect the console will log I am clicked, but it does not appear which is unexpected.

enter image description here

App.js

                <div
                  className={classes.searchIcon}
                  onClick={() => {
                    console.log("I am clicked");
                  }}
                >
                  <SearchIcon />
                </div>

CodeSandbox:

Edit magical-solomon-yi3xs

like image 527
CCCC Avatar asked Dec 06 '25 13:12

CCCC


1 Answers

You have pointerEvents: none in your CSS, which is disabling clicking. Also, I'd recommend using a button instead of a div for accessibility purposes (you can style it to look however you want).

const useStyles = makeStyles((theme) => ({
  searchIcon: {
    padding: theme.spacing(0, 1),
    height: "100%",
    //pointerEvents: "none", <-- remove this
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    cursor: "pointer",
    zIndex: 200
  }
}));

The more accessible JSX (with a button):

<button
  className={classes.searchIcon}
  onClick={() => {
    console.log("I am clicked");
  }}
>
  <SearchIcon />
</button>
like image 169
Nick Avatar answered Dec 08 '25 16:12

Nick