Arttu
Arttu

Reputation: 251

Material UI hide element onClick or when checkbox is checked

I'm trying to hide element when button is clicked or when checkbox is checked. I tried to Google the solution but can't find anything. Can anyone help with this?

I want to hide that first MenuItem which has Input inside of it and it needs to be hidden when Button is clicked which is inside of second MenuItem or Checkbox is checked which is inside of third MenuItem. Also it needs to return back to normal when clicking Button again, or when checkbox is not checked.

<MenuItem>
    <Input />
<MenuItem/>
<MenuItem>
    <Button onClick={handleClick}>
        Hide onClick!
    </Button
</MenuItem
<MenuItem>
    <Checkbox />
</MenuItem>

I assume I need to do something like this. Inside handleClick I need to set input MenuItems display to none.

const [hide, setHide] = useState(false);

const handleClick = () => {
   
}

So basically I think I need to change style of element onClick or checked. I don't have much to show because I don't have any clue how to do that.

Upvotes: 0

Views: 3037

Answers (2)

Rajiv
Rajiv

Reputation: 3772

use the conditional rendering for this.

{hide && (
  <MenuItem>
    <Input />
  </MenuItem>
)}

now, whenever the hide state is true, <Input/> menuItem will be rendered and for false, it'll be hidden.
To mutate the hide state from both CheckBox and Button, create a handler that will set the state.

const toggleHide = () => {
  setHide((oldState) => !oldState);
};

Now call this toggleHide function on the click of the Button and onChange of the Checkbox.
Note:- for better result onClick listeners can be added to the MenuItem instead of the Button and CheckBox.

Edit tender-hamilton-x041s

Upvotes: 1

amirreza mojarad
amirreza mojarad

Reputation: 331

change this

<MenuItem>
<Input />
<MenuItem/>

to this

{ hide && (<MenuItem>
<Input />
<MenuItem/>) }

and the function must be like this

const handleClick = () => {
 setHide(prev => !prev)

 }

Upvotes: 2

Related Questions