During a recent keynote, I heard that in the future versions of React, it's recommended to hide a component or element using the hidden
property. However, I'm curious about how to incorporate a transition effect when toggling the visibility of an element.
Here's a simple example. If you remove the hidden
property, the transition will occur.
class App extends React.Component {
state = {
isHidden: true
}
toggle = () => {
this.setState({
isHidden: !this.state.isHidden
});
}
render() {
const className = this.state.isHidden ?
'is-hidden' : 'is-visible';
return (
<div>
<button onClick={this.toggle}>toggle</button>
<div className={'elm ' + className} hidden={this.state.isHidden}>
Hello world
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
.elm {
transition: opacity .5s ease;
}
.is-visible {
opacity: 1;
}
.is-hidden {
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Is there a way to utilize the hidden
property while still implementing CSS transitions?