the code is in this codesandbox.io - https://codesandbox.io/s/react-slider-forked-wu0q6
if (newActiveIndex === slides[slides.length - 1].index) {
const { slides } = this.state;
// index (10-3) to (10)
const add = slides.slice(slides.length - 3);
const newSlides = slides.unshift(add);
console.log("newSlides", newSlides);
this.setState({
slides: newSlides
});
} else {
this.setState({
slides: slides
});
}
};
I tried using unshift method, but when i console log it, it returns a number and not an array. what i want is [0,1,2,3,4,5] becomes [3,4,5,0,1,2]
You used two component each one have a state. When you change the state from the dots component the image component has no idea that there is a change. So the solution is to add the active state in your App.js and pass it as props for both components => if you change it from dots the image will have the latest active index
import React from "react";
import ImageSlider from "./components/ImageSlider";
import SliderDots from "./components/SliderDots";
import "./styles.css";
const SliderData = require("./SliderData.json");
/**
* Convert this to class since you will be working with class!
*/
export default class App extends React.Component {
state = {
selectedIndex: 2
};
setSelectedIndex = (i) => {
this.setState({ selectedIndex: i });
};
render() {
return (
<>
<ImageSlider
slides={SliderData}
selectedIndex={this.state.selectedIndex}
setSelectedIndex={this.setSelectedIndex}
/>
<SliderDots
slides={SliderData}
selectedIndex={this.state.selectedIndex}
setSelectedIndex={this.setSelectedIndex}
/>
</>
);
}
}