I really need your help. I have an array useState with elements 'Screen'. I dynamically add elements to useState to add them to the page.
I need to make small changes to each of these elements, the "ID" variable in the Screen. I want to select on creation through a for loop. I don't know how to do it. Please look at an example. I simplified it for better understanding
//Screen.js
let ID
import React, {useEffect} from "react";
const Screen =()=>{
useEffect(()=>{
socket.on(ID,async () => {console.log(ID)})
},[])
return(
<canvas id={ID} className='canvas' width={600} height={400}> </canvas>
)
}
export default Screen
//List.js
import Screen from './Screen';
import React, {useEffect, useState} from "react";
const List = ()=>{
const [state, setState] = useState([]);
useEffect(()=>{
for (let i=0;i<5;i++){
setState(state =>[...state, <Screen key={i}/>])
}
},[])
return(
<div>
{state}
</div>
)
}
export default List
Your answer is a bit confusing, but i would like to try to give you an answer.
Is the below solution what are you looking for?
const Screen = ( {id} )=> {
useEffect(()=> {
socket.on(id,async ()=> {console.log(id)})
}, [id])
return <canvas id={id}
className='canvas'
width={600}
height={400}
/>
}
const List = ()=>{
const [state, setState] = useState([]);
useEffect(()=>{
for (let i=0;i<5;i++){
setState(state =>[...state, <Screen key={i} id={i}/>])
}
},[])
return(
<div>
{state}
</div>
)
}