2

I'm trying to open Material UI Box component when clicking on Button and close Box when clicking Button again. I tried to search solution from google but can't really find anything simple. I need very basic solution for this. I don't have any solutions what I've tried because I just wondering how to do that.

I assume I need these handlers and some code inside them:

const [show, setShow] = useState(null);

const handleOpen = event => {
    setOpen(event.currentTarget);
};

const handleClose = () => {
    setOpen(null);
};

Here is the Button component which should open and close Box component. There I need two functions. When I click button it sets Box !null if it's null and null if it's !null:

<Button 
    className={classes.button}
    onClick={handleOpen}
>
    Click
</Button>
<Box className={classes.box}>
    // Some content
</Box>
Arttu
  • 191
  • 2
  • 5
  • 16
  • Does this answer your question? [React Button Click Hiding and Showing Components](https://stackoverflow.com/questions/59624519/react-button-click-hiding-and-showing-components) – Rajiv Jan 19 '21 at 09:53

1 Answers1

21

You need to use a state to show/hide your component. You can handle that very simple like this (using Hooks)

import React, { useState } from 'react';

const Component = () => {
  const [show, setShow] = useState(false);
  return(
    <>
      <button onClick={() => setShow(prev => !prev)}>Click</button>
      {show && <Box>This is your component</Box>}
    </>
  );
}

export default Component
Hai Huynh Ngoc
  • 359
  • 3
  • 6