Using React.
If I had an array like:
[ data:
title: foo1
body: bar1
title: foo2
body: bar2
title: foo3
body: bar3
]
And I wanted to display a single body and title at one time on my page and loop through these elements (have a paragraph that changes its contents routinely).
So far I specify which data I want using this:
let specificBody = this.state.data[x].body; //loop through different elements of array on timer
let specificTitle = this.state.data[x].title;
let specificPosted_By = this.state.data[x].posted_by;
Is there any way to increment the value of x so that I can display a different body and title? Or is there another way of achieving this aim?
All help greatly appreciated.
CodePudding user response:
Some pseudo code, untested:
const [index, setIndex] = useState(0)
useEffect(() => {
const interval = setInterval(() => { /*todo reset at max value*/ setIndex(index 1) }, 10000)
return () => clearInterval(interval)
},[])
and then use index here:
this.state.data[index].body;
CodePudding user response:
This is an example of how you can use setInterval to update the active index periodically.
Your render will then display the text of the active object in the array.
const data = [{ title, body },{ title, body }, { title, body }]
const Component = () => {
const [active, setActive] = useState(0);
useEffect(() => {
//This is how you use setInterval to change the active index every 5 seconds
setInterval(() => {
setActive( previous => {
if (previous === data.length) {
return 0;
} else {
return previous 1;
}
})
}, 5000) //Change every 10 seconds
},[])
return <div>{data[0].title}</div>
}
CodePudding user response:
It looks like you're trying to accomplish two things:
- Increment the specific array position
- Do this automatically using a timer.
The snippet of code doesn't show what loop logic you're using, but assuming you're going to implement a setInterval inside a useEffect hook, you want to create an independent state variable for 'x' (which marks the array index on your data object).
You can then set a conditional within the useEffect hook, like this:
const intervalId = setInterval(() => {
if(x <= data.length) {
setData(data[x])
}
else {
setState({
x = 0;
})
};
}, 5000);
return () => clearInterval(intervalId);
}, [data, x])
CodePudding user response:
probably a better approach is to divide it into two components, one that hold the data and has the rotation logic and another one that is just presentation
something like this
const Article = (title, body) => {
return <div>...</div>
}
const ArticleCarousel = (data, time) => {
const [index, setIndex] = useState(0)
useEffect(() => {
const interval = setInterval(() => {
setIndex(i => (i 1) % data.lenght)
}, time)
return () => clearInterval(interval)
})
return <Article {...data[index]} />
}
