Reputation: 1797
I have a component (Father.js) that have these 2 variables that use state:
const [streetAddress1, setstreetAddress1] = useState();
const [streetAddress2, setstreetAddress2] = useState();
And also a function declared this way:
const setValues = (value, name) => {
if(name === 'streetAddress1'){
setStreetAddress1(value);
}
else if(name === 'streetAddress2'){
setStreetAddress2(value);
}
}
And then I have a child component which is called this way:
<Child objectNr="1" setValues={setValues} />
<Child objectNr="2" setValues={setValues} />
The Child components have input fields that on blur will set the address. I coded it this way:
<input
type="text"
onBlur={ (e) => setValues(e.target.value, `streetAddress${objectNr}`)} />
This works. However, having a lot of similar variables that uses state, I wonder if it is possible in the function setValue to just run the set-method depending on the incoming string. So as the first child is sending th string "streetAddress1" I would like the function setValue to just run the set-method for that variable, without needing to run a lot of if-statements. is this possible?
Upvotes: 1
Views: 43
Reputation: 371193
It sounds like you might want to use an object or array in state instead:
const [streetAddresses, setStreetAddresses] = useState({});
<Child objectNr="2" setStreetAddresses={setStreetAddresses} />
onBlur={
(e) => {
setStreetAddresses(addresses => ({
...addresses,
[objectNr]: e.target.value
}));
}
Or you could put the index and/or state combination logic into the parent instead, whatever is cleaner for your setup:
// in father.js:
const makeSetAddress = objectNr => e => {
setStreetAddresses({
...streetAddresses,
[objectNr]: e.target.value
});
};
// and pass it down:
<Child objectNr="2" setAddress={makeSetAddress(2)} />
// might be able to omit objectNr above
// if it isn't being used anywhere else but the state setter
onBlur={setAddress}
Upvotes: 2