I have three component in screen with same size but different static data.
I wan't to replace the every 5 seconds on the screen in the same area(display position is fix). For ex. I have <FeedbackComp1>
, <FeedbackComp2>
and <FeedbackComp3>
. So, i want display and replace the component every 5 seconds.
Display: first time render the screen display the <FeedbackComp1>
and then replace the place <FeedbackComp2>
and then <FeedbackComp3>
and then <FeedbackComp1>
so on.
if possible this functionality in array map() function so I also ready for that.
Thank You.
CodePudding user response:
Something like this should do the trick.
import { useEffect, useState } from 'react'
// placeholders for your actual components.
const FeedbackComp1 = () => <></>
const FeedbackComp2 = () => <></>
const FeedbackComp3 = () => <></>
const MyComponentSwitcher = () => {
const [index, setIndex] = useState(0)
const components = [<FeedbackComp1/>, <FeedbackComp2/>, <FeedbackComp3/>]
useEffect(() => {
const interval = setInterval(() => {
setIndex(currentIndex => (currentIndex 1) % components.length)
}, 5000)
return () => clearInterval(interval)
}, [])
return components[index]
}
Short explanation:
- The
index
state-variable holds the index we're currently at. - The
components
array holds the components you want to switch between. - The
useEffect
initializes an interval of 5000 ms, so that every 5 seconds, it will set the index to one more than it currently is, using the remainder operator%
to ensure we never have an index outside the array.- Note that the
setIndex
doesn't take in a new value, but rather a callback. This allows us to automatically set the value to one higher than before, without having to reference the value when the component is initialized. React reference.
- Note that the
- The
return
statement simply returns the current component.