Issue
I have a form that gets it's input fields dynamically, it can have hundreds of fields so i can't create a state individually, I was planning on doing something like using an object using the unique key of a form field but need some help.
Suppose the form has fields like this.
<form>
{inputFields.map((i) => {
<input type={i.type} />
})}
</form>
Now i would need a state like the one below
inputState = {
"INPUT_FIELD_NAME1": "INPUT FIELD VALUE 1",
"INPUT_FIELD_NAME2": "INPUT FIELD VALUE 2",
"INPUT_FIELD_NAME3": "INPUT FIELD VALUE 3",
}
I need help with this, how do i set values in such a manner in my input onChange and how do i access the values from the state and use them for the matching input field?
Solution
As per my understanding and knowledge, you have to update your dynamic structure like given as below
<form>
{inputFields.map((i) => (
<input
type={i.type}
name={`INPUT_FIELD_NAME${i.id}`}
onChange={handleChange}
/>
))}
</form>
Also have to update your react state on input change like
const [inputState, setinputState] = useState({});
const handleChange = (e) => {
const { name, value } = e.target;
setinputState({
...inputState,
[name]: value
});
};
I hope it will work for you! Thanks.
Answered By - Parth Navadiya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.