Typical way
The most common pattern to this is selectively rendering the element based on state.
class Foo extends React.Component {
state = { showing: true };
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
{ showing
? <div>This is visible</div>
: null
}
</div>
)
}
}
Alternative
You can also use a style based on state. This is less common, but can be useful when you have complex components inside that div - one recent example, I had a complex non-React D3 graph within a toggle-able component, initially, I used the first method above, but caused quite a bit of lagging when flicking the div on/off because D3 was cycling up again.
Generally use the first approach though, unless you have a reason to use the alternative.
class Foo extends React.Component {
state = { showing: true };
render() {
const { showing } = this.state;
return (
<div>
<button onClick={() => this.setState({ showing: !showing })}>toggle</button>
<div style={{ display: (showing ? 'block' : 'none') }}>This is visible</div>
</div>
)
}
}
Note
I use the ?:
ternary operator instead of &&
- I'm a strong believer that the use of &&
is relying on a side effect of that operator to achieve a certain outcome. It works, don't get me wrong, but the ternary operator, in my opinion, is far more expressive and was designed to be a conditional.
This last bit is just my opinion - so I'm not questioning the use of &&
.