Best way to animate the hidden property on a component

Viewed 90

I saw in a keynote that in upcoming versions of React, it is wise to hide a component or an element with the property hidden. However, I was wondering how you could add an effect onto the transition when e.g. toggling the visibility of an element.

Here a little example. If you drop the hidden property, the transition takes place.

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>

How can I use the hidden property and still use CSS transitions?

1 Answers

I don't know for sure, but I assume that the React property isHidden is doing a CSS display:none; behind the scenes. You can't transition the display property in CSS.

So if the transition is important, I'd hide the elements with CSS opacity:0 on load then add the visible class when you're ready.

Related