Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React and Material UI: show and hide component onClick

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>
like image 697
Arttu Avatar asked Oct 26 '25 02:10

Arttu


1 Answers

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
like image 148
Hai Huynh Ngoc Avatar answered Oct 28 '25 16:10

Hai Huynh Ngoc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!