Reputation: 1985
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"
}
};
Upvotes: 3
Views: 3052
Reputation: 51
Solution: https://codesandbox.io/s/react-example-lyf3f
I made a few edits to your sandbox to achieve the desired functionality.
options
array into state
this.state.current
as a prop
to an Option
componenttoggleIn
animation using an @keyframes to create the desired animationkey
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