so I've got a header that cycles through 4 images every 5 seconds. The user can also cycle through these images themselves using 5 radio buttons.
The styling for the active/checked radio button is applied when the user clicks it themselves, however, if the timer switches the image the active radio button remains unchanged.
I know this is the expected behaviour based on my code below, I'm just wondering how I would go about changing the checked radio button to match it's current image!
Any help would be appreciated!
constructor(props) {
super(props);
this.state = {
time: 0,
start: 0,
currentIndex: 0
};
this.setIndex = this.setIndex.bind(this);
this.startTimer = this.startTimer.bind(this);
this.resetTimer = this.resetTimer.bind(this);
}
componentDidMount() {
this.startTimer();
}
componentDidUpdate() {
if (this.state.time === 5) {
this.setIndex(this.state.currentIndex + 1);
}
}
startTimer() {
this.timer = setInterval(
() =>
this.setState({
time: this.state.time + 1
}),
1000
);
}
resetTimer() {
this.setState({ time: 0 });
}
setIndex(index, e) {
console.log("changing");
if (index < 0) {
index = headers.length - 1;
}
if (index >= headers.length) {
index = 0;
}
this.setState({
currentIndex: index,
time: Date.now() - this.state.start
});
this.resetTimer();
}
... skipped code
<div className="carousel">
<img
alt="carousel-header"
className="background-img"
src={headers[this.state.currentIndex].image}
/>
<div className="buttons-container">
<input
type="radio"
value="1"
defaultChecked
name="index"
onClick={() => this.setIndex(0)}
></input>
<input
type="radio"
value="2"
name="index"
onClick={() => this.setIndex(1)}
></input>
<input
type="radio"
value="3"
name="index"
onClick={() => this.setIndex(2)}
></input>
<input
type="radio"
value="4"
name="index"
onClick={() => this.setIndex(3)}
></input>
</div>
</div>