I am looking for a way to create a fade in/out effect on a component whenever its prop changes. Unlike basic examples that toggle styles based on boolean conditions, I want the element's visibility state to be updated directly through prop changes.
For instance, in my code sandbox project, I have several buttons that, when clicked, will change the displayed text. I would like to implement a feature where this text fades in and out each time a user selects 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 });
};
// used solely for testing 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"
}
};