I have a state with an array of objects:
const [Value, setValue] = useState([{ Width: null, Length: null }, { Width: null, Length: null }])
And also, I have a component from which I want to get the value for Value
using setValue
.
Here is the code:
const [Value, setValue] = useState([{ Width: null, Length: null }, { Width: null, Length: null }])
export function SimpleComponent({ Width, setWidth, Length, setLength }) {
return (
<>
<input
type="number"
value={Width || ""}
onChange={event => setWidth(event.target.value)}
/>
<input
type="number"
value={Length || ""}
onChange={event => setLength(event.target.value)}
/>
</>
)}
{Value.map((item, i) => {
return (
<div key={i}>
<SimpleComponent
Width={item.Width}
setWidth={???}
Length={item.Length}
setLength={???}
/>
</div>
)
})
}
And I need to specify the Width
and Length
value for the current component SimpleComponent
in the attributes setWidth
and setLength
, specified with "???" signs in the code.
I tried to solve this in some ways, but without success.
Please help!
3
Answers
Either you can write 2 functions, one for length and one for width
Or you can combine these into one single function
You need to define function that, when a new width should be set at index i in the
Value
array, copies the previous array and replaces the element at index i with a new entry.You can define your functions like this:
Then render components like this: