I am working on a project in which
1- i have to display 50 circle on screen. 2- My data is streaming in real time. data in form of object in which i am storing {id:0,color:"red"}. So for example if id in real time data is {id:10,color:"pink"}. then the circle number 10 color should be pink.for Simplicity I am generating a custom hook for generating a random number. //RandomNumber() is custom hook.
const [random,setRandom]=RandomNumber();
useEffect(()=>{
console.log(random);
if(random>10 && random<200)
{
setColor("Red")
}
else if(random>500)
{
setColor("brown")
}
})
return (
<div className="show-data" onWheel={onWheelHandler}>
{
Array.apply(null, { length: 50 }).map((a, i) => (
pad=="60px"?
<button className="wave-circle" style={{backgroundColor:color,padding:pad}} onMouseOver={onMouseOverHandler} onClick={onClickHandler} onMouseOut={onMouseLeaveHandle } key={i}>
{i 1}
</button>
:
<button className="wave-circle" style={{backgroundColor:color,padding:pad}} value={i 1} onMouseOver={onMouseOverHandler} onClick={onClickHandler} onMouseOut={onMouseLeaveHandle} key={i}>
</button>
) ,
)
}
CodePudding user response:
(1) the array of "circle" data would need to be stored in state, (2) each time streaming data is processed map the old array to a new array and update the specific element by matching id.
Example:
function App() {
const [circles, setCircles] = React.useState(
Array.from({ length: 50 }, (_, id) => ({
id,
color: "red"
}))
);
// Simulate data on interval
React.useEffect(() => {
const tick = () => {
setCircles((circles) => {
const id = Math.floor(Math.random() * circles.length);
return circles.map((c) => (c.id === id ? { ...c, color: "brown" } : c));
});
};
const timer = setInterval(tick, 250);
return () => clearInterval(timer);
}, []);
return (
<div className="App">
{circles.map(({ id, color }) => (
<div key={id} className="circle" style={{ backgroundColor: color }} />
))}
</div>
);
}