Search code examples
javascriptreactjscomponents

Setting onClick to false


I currently have a table using a slider to provide additional details for a table. When the slider component opens I have an X to close to the slider. I am attempting to have that X close the slider and have the table in its original form appear.

Here is a code sandbox: code sandbox

Slider component :

function ExpandToggle(isOpenProps) {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = () => {
    setIsOpen(!isOpen);
  };

  return (
    <>
      <Button>
        <ArrowForwardIosIcon size="small" onClick={toggle} />{" "}
      </Button>
      <SliderInfo open={isOpen} />
    </>
  );
}

SliderInfo component with onClick={open=false}

export default function SliderInfo({ open }) {
  const classes = useStyles();



  return (
    <Slide direction="left" in={open} mountOnEnter unmountOnExit>
      <div className={classes.root}>
        <Grid container>
          <Grid item>
            <Typography variant="h6">Vanila Ice Cream</Typography>
          </Grid>
          <Grid item>
            <Typography variant="h6">Chocolate Ice Cream</Typography>
          </Grid>
          <Grid item>
            <Typography variant="h6">Strawberry Ice Cream</Typography>
          </Grid>
          <Grid item>
            <Typography variant="h6">Sherbert </Typography>
          </Grid>
          <Grid item>
            <Typography variant="h6">None</Typography>
          </Grid>
          <Grid item>
            <Button>
              <CloseIcon onClick={open=false} />
            </Button>
          </Grid>
        </Grid>
      </div>
    </Slide>

On CloseIcon I have an onClick that i'm trying to set open which is passed from Slider to false so it can close the slider component. At the moment upon clicking on the CloseIcon it is not do anything.


Solution

  • Don't modify props directly.

    Pass in the toggle function just like you passed in the open variable, and call it instead.

    <SliderInfo open={isOpen} toggleOpen={toggle} />
    
    // In Sliderinfo
    export default function SliderInfo({ open, toggleOpen }) {
    ...
    <CloseIcon onClick={toggleOpen} />
    

    If your toggle doesn't serve the same purpose, create a new function that only sets isOpen to false and use it instead.

    Also remember that onClick expects a function. So the open=false is actually getting executed during render, not after a click. Correct inline format would be onClick={(e) => {//do stuff}}.