export default function App() {
const measurementData = {
id: 301,
name: "Topwear",
measurements: [
{ id: 1, name: "neck" },
{ id: 2, name: "shoulder" }
]
};
return (
<div className="App mt-5">
<h1>Update Measurement Data</h1>
{measurementData.measurements?.map((data) => {
return (
<div className="d-flex">
<label className="col-form-label">{data.name}</label>
<input type="number" name={data.name} className="form-control"/>
</div>
);
})}
</div>
);
}
Basically, I'm mapping through the object. I just want to add new property called value and save the value that we get from the input field(value: 20) in the end of measurements array of object in measurementData.
// example: the object should be like this after enter values in input field
{
id: 301,
name: "Topwear",
measurements: [
{ id: 1, name: "neck", value: 20},
{ id: 2, name: "shoulder", value: 40 }
]
}
CodePudding user response:
You can do this by creating a state for the measurements
. This allows React to re-render the UI when the user types something in the inputs. I moved the measurementData
code outside the component, if this is dynamic you can simply place it back.
When mapping over the measurements
to render them we provide the inputs with a value
prop and pass the current value for that measurement. If there is no value yet we default to 0
.
import { useState } from "react";
const measurementData = {
id: 301,
name: "Topwear",
measurements: [
{ id: 1, name: "neck" },
{ id: 2, name: "shoulder" },
],
};
export default function App() {
// create the state
const [measurements, setMeasurements] = useState(
measurementData.measurements
);
// create the onChange handler
const handleOnChange = (e) => {
const value = e.target.value;
const name = e.target.name;
setMeasurements((prevState) => {
// map over the prev measurements
return prevState.map((measurement) => {
// if the name is not the same just return the measurement
if (measurement.name !== name) return measurement;
// else return a new object with the prev measurement and the new value
return {
...measurement,
value: value,
};
});
});
};
return (
<div className="App mt-5">
<h1>Update Measurement Data</h1>
{measurements.map((measurement) => {
return (
<div className="d-flex">
<label className="col-form-label">{measurement.name}</label>
<input
type="number"
name={measurement.name}
value={measurement.value ?? 0}
onChange={handleOnChange}
className="form-control"
/>
</div>
);
})}
</div>
);
}