jamesvphan
jamesvphan

Reputation: 1985

Trigger CSS Transition on component prop changes

I want to fade in/out a component whenever its prop changes. Some basic examples I've found achieve this via a boolean condition that toggles the element's styles, but I want to update the toggle state via a prop change.

For example, in my code sandbox, I have a few buttons that when clicked, will update the text on screen. I want to be able to fade in/out this text whenever the user clicks on a different option.

class Example extends Component {
  constructor(props) {
    super(props);
    this.state = {
      current: "dog",
      isVisible: false
    };
  }

  componentDidMount() {
    this.setState({ isVisible: true });
  }

  handleOnClick = option => {
    this.setState({ current: option });
  };

  // only used to test css transition
  forceToggleState = () => {
    this.setState(prevState => ({ isVisible: !prevState.isVisible }));
  };

  render() {
    const options = ["dog", "cat", "rabbit"];
    return (
      <div>
        {options.map((option, index) => (
          <button onClick={() => this.handleOnClick(option)} key={index}>
            {option}
          </button>
        ))}
        <div style={this.state.isVisible ? styles.toggleIn : styles.toggleOut}>
          {this.state.current}
        </div>
        <button onClick={this.forceToggleState}>toggle me</button>
      </div>
    );
  }
}

const styles = {
  toggleIn: {
    opacity: 1,
    transition: "all 0.5s ease",
    border: "1px solid red"
  },
  toggleOut: {
    opacity: 0,
    transition: "all 0.5s ease-in"
  }
};

current sandbox

Upvotes: 3

Views: 3052

Answers (1)

Brett S.
Brett S.

Reputation: 51

Solution: https://codesandbox.io/s/react-example-lyf3f

I made a few edits to your sandbox to achieve the desired functionality.

  1. Move options array into state
  2. Pass this.state.current as a prop to an Option component
  3. Create a toggleIn animation using an @keyframes to create the desired animation
  4. Set the key prop equal to this.props.current in the Option component to make sure the DOM element remounts any time the this.props.current changes. This will ensure our animation runs each time the this.props.current changes.

Upvotes: 5

Related Questions