Good Morning,
I'm creating an react app, this application will have four "sides" and each side can have different values so I mapped the same component 4 times:
:[...Array(item)].map((data) =>
<Side
key={ data }
Style='wall-holder'
InputClass='input-height'
/>
)
}
So each Side could work as its own thing, in each side the user can input an specific value using the inputs that exists in the Side component:
Side Component= input= 1, input =2;
Side Component= input=3, input =5;
Side Component= input=3, input =5;
Side Component= input=3, input =5;
note: is only one component Side, I just mapped it 4 time so i could reuse it
Now I want to be able to get all of those inputs in an array or object so I can add all of the input values, however when I try to send it to a global state with the api context, it only keeps the last added value, I understand why is this happening(kinda), but I dont know yet how to solve this problem
Keep a state in your parent component like below. use index to update each input state of Side components.
import {useState} from "react";
const ParentComp = () => {
const [state, setState] = useState({});
return [...Array(item)].map((data, dataIndex) =>
<Side
key={ data }
Style='wall-holder'
InputClass='input-height'
setState={setState}
dataIndex={dataIndex}
/>
)
}
In your Side component.
<input
onChange={e =>
props.setState(prevState => {
return { ...prevState, [props.dataIndex]: e.target.value };
})
}
/>;