Issue
I am using React. When a button is clicked, the text changes. I would like to have the current text fade out and then the new text fade in when the button is clicked.
I tried implementing solutions from other stack overflow posts, but to no avail.
Here is the codepen https://codepen.io/Jamece/pen/PoObBEN
const duration =1000;
//creating main React component with state being random numbers that will be an index for the quotes and color array.
class QuoteMachine extends React.Component {
constructor(props) {
super(props);
this.state = {
randomIndexQuote: 0,
randomIndexColor: 0,
fadeTransition: null,
fadeState: "fade-in"
};
this.handleClick = this.handleClick.bind(this);
}
//upon click, a random number will be generates and state will be updated
handleClick() {
const timeout = setTimeout(() => {
this.setState({
randomIndexQuote: Math.floor(Math.random() * quotes.length),
randomIndexColor: Math.floor(Math.random() * colors.length),
fadeTransition: null,
fadeState: 'fade-in'
});
}, duration);
clearTimeout(this.state.fadeTransition);
this.setState({
fadeState: "fade-out",
fadeTransition: timeout
});
}
render() {
//variables holding state index
const quoteOutput = quotes[this.state.randomIndexQuote].quote;
const authorOutput = quotes[this.state.randomIndexQuote].author;
//variables for random color styles
const textStyle = {
color: colors[this.state.randomIndexColor],
transition: "all 2s ease"
};
const backgroundStyle = {
backgroundColor: colors[this.state.randomIndexColor],
transition: "all 2s ease"
};
return (
<div className="container-fluid px-0">
<div
className="d-flex justify-content-center align-items-center main"
id="quote-box"
style={backgroundStyle}
>
<div className="white-box">
<div
className={"fade-wrapper ${this.state.fadeState}"}
style={{ transitionDuration: "${duration}ms" }}
>
<p id="text" style={textStyle} className="text-center">
"{quoteOutput}"
</p>
<p id="author" style={textStyle} className="text-end">
{authorOutput}
</p>
</div>
CSS
.fade-wrapper {
transition: opacity ease-in-out;
}
.fade-out {
opacity: 0;
}
.fade-in {
opacity: 1;
}
Thank you.
Solution
You could simply set the opacity to go from 1 to 0 and back to 1. You have everything ready with the color animation, all you need to do is add the opacity alongside the colors - (https://codepen.io/Brisingr_1/pen/NWwjWLx)
this.state = {
...,
opacity: 1
};
const timeout = setTimeout(() => {
this.setState({
...,
opacity: 1
});
}, duration);
clearTimeout(this.state.fadeTransition);
this.setState({
...,
opacity: 0,
});
const textStyle = {
...,
opacity: this.state.opacity,
};
Answered By - Alex Popov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.