I have a component with a single input element and I am creating multiple components by looping. Suppose I have created 3 components by looping and it creates 3 inputs as well. So I do I get the values of all the three input like input_values = [valueofFirstInput, valueofSecondInput, valueofThirdInput]
function Home(){
const [multipleQuestions, setMultipleQuestions] = useState([0, 1, 2]);
return(
{multipleQuestions.map((data, index) => {
return (
<div key={data}>
{<MultipleInputs />}</div>
)
})}
)
}
function MultipleInputs() {
function getinputValues(e) {
e.target.value;
}
return <input onChange={(e) => getinputValues(e)} />;
}
2
Answers
You can make your custom input component a controlled input by allowing the value and a callback for when the value changes to be passed in as props. Then, you can store all the input values in state.
Generally you would treat those child components as controlled components which can share state. You would create a handler in the parent component and pass down a reference to it to each input component. They can then call that handler when their
change
event is fired.In this example I’ve created a sample dataset which I’m passing into
Home
. Each object in the dataset has an id (which we can use for a key instead of themap
index), a name, and a label.In
Home
we create state for the input values. This is an object which pairs a key (the inputname
) with a value.Here also is the handler which destructures the
name
andvalue
from the changed input, and updates the state with that information.(There is also a
useEffect
which logs the changes to the state as each input is changed so you can see it working.)When we iterate over the dataset we return an
Input
element passing down the name, type, value (obtained from state), and label as props along with the handler reference. In theInput
component we attach these props as attributes to the input element, and assign the handler to theonChange
listener.