Binding Inputs to an Object in React
Let the state store an object:
const initObj = {
prop1: 'value1',
prop2: 'value2',
prop3: 'value3',
}
function App() {
const [obj, setObj] = useState(initObj);
return <div>
{obj.prop1}-{obj.prop2}-{obj.prop3}
</div>;
}
Let's output each property of our object in a separate input:
function App() {
const [obj, setObj] = useState(initObj);
return <div>
<input value={obj.prop1} />
<input value={obj.prop2} />
<input value={obj.prop3} />
<br />
{obj.prop1}-{obj.prop2}-{obj.prop3}
</div>;
}
Let's now bind the onChange event to each input. As a handler, we'll assign one common function:
function App() {
const [obj, setObj] = useState(initObj);
return <div>
<input value={obj.prop1} onChange={event => handleChange('prop1', event)} />
<input value={obj.prop2} onChange={event => handleChange('prop2', event)} />
<input value={obj.prop3} onChange={event => handleChange('prop3', event)} />
<br />
{obj.prop1}-{obj.prop2}-{obj.prop3}
</div>;
}
As you can see, the handleChange function takes the name of the corresponding property of the object as its first parameter.
Let's write the implementation of our function:
function handleChange(prop, event) {
const copy = Object.assign({}, obj);
copy[prop] = event.target.value;
setObj(copy);
}
This implementation works, but it can be simplified by using computed names of object properties:
function handleChange(prop, event) {
setObj({...obj, ...{[prop]: event.target.value}});
}
Let's put all the code together:
function App() {
const [obj, setObj] = useState(initObj);
function handleChange(prop, event) {
setObj({...obj, ...{[prop]: event.target.value}});
}
return <div>
<input value={obj.prop1} onChange={event => handleChange('prop1', event)} />
<input value={obj.prop2} onChange={event => handleChange('prop2', event)} />
<input value={obj.prop3} onChange={event => handleChange('prop3', event)} />
<br />
{obj.prop1}-{obj.prop2}-{obj.prop3}
</div>;
}
Let the state store an object with a date:
const initDate = {
year: 2025,
month: 12,
day: 31,
}
Display in a paragraph the year, month, and day of the date stored in the state, as well as the day of the week corresponding to it.
Modify the previous task by adding three inputs for editing the date.