'React, Resolving read only error for form field with dynamic mapped inputs
I'm making a reusable form that is the base for various forms which will add inputs based on the needs of the parent Form, my problem is that while I have an onChange for the inputs I continue to get this message "index.js:1 Warning: You provided a value prop to a form field without an onChange handler. This will render a read-only field. If the field should be mutable use defaultValue. Otherwise, set either onChange or readOnly."
loginForm.jsx
import React, {useState} from 'react';
import Form from './common/form';
const LoginForm = () => {
const [data, setData] = useState ({username: "", password: ""})
const inputList = [
{name:"username", label: "Username", value: data.username},
{name:"password", label: "Password", value: data.password, type:"password"},
]
const doSubmit = () => {
console.log("Submitted")
}
return (
<div>
<h1>Login</h1>
<Form inputList={inputList} setData={setData} doSubmit={doSubmit} label="Login"/>
</div>
)
}
form.jsx
import React from 'react';
import Input from './input';
const Form = ({inputList, setData, doSubmit, label}) => {
const handleSubmit = e => {
// will evaluate errors, and then call parent function
doSubmit()
}
const handleChange = (currentTarget) => {
const { name, value } = currentTarget;
setData(prevData => ({ ...prevData, [name]: value}));
};
return (
<form>
{
inputList.map(({name, label, value, type="text", error}) =>
<Input
key={name}
type={type}
value={value}
label={label}
error={error}
onChange={(e) => handleChange(e.target)}
/>
)
}
<button className="btn btn-primary" onClick={() => handleSubmit()}>
{label}
</button>
</form>
)
}
input.jsx
import React from 'react';
const Input = ({name, label, value, type, error}) => {
return (
<div className="form-group">
<label htmlFor={name}>{label}</label>
<input
id = {name}
name = {name}
label = {label}
value = {value}
type = {type}
error = {error}
className="form-control"
/>
</div>
);
}
export default Input
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
