I am trying to receive an array from dynamic input but document.querySelector
is returned undefined
{chapitreList.map((partItem,index) => {
return <div>
<input type="text" name='soldc' id='soldc' className ="form-control" placeholder={partItem.chapitreDepense} />
</div>
}
const show_element = (e) => { console.log(document.querySelector('#soldc')[0].value) }
CodePudding user response:
The issues
document.querySelector
returns a single DOM node, not aNodeList
(likequerySelectorAll
does.- In HTML you cannot have multiple nodes with the same ID
- In React, avoid using native DOM calls (document.querySelector, etc.)
The solution
Instead of using imperative methods of retrieving multiple input values, use a declarative state to hold your inputs and update the state on change.
function App() {
const chapitreList = [{ chapitreDepense: "1" }, { chapitreDepense: "2" }];
const [formData, setFormData] = useState(Array(chapitreList.length).fill(""));
console.log(formData); // access your array
return (
<>
{chapitreList.map((partItem, index) => (
<div key={index}>
<input
onChange={(e) =>
setFormData((prev) => {
prev[index] = e.target.value;
return [...prev];
})
}
type="text"
name="soldc"
className="form-control"
placeholder={partItem.chapitreDepense}
/>
</div>
))}
</>
);
}
Read more about thinking in React