I am working with forms in React, using function components for the first time. Either I am going crazy, or this should work with no issues...
import React, {useEffect, useState} from 'react';
function ChangePasswordComponent(props) {
const {onChangePassword} = props;
const [isValid, setIsValid] = useState(true);
const [form, setForm] = useState({
password: undefined,
confirm: undefined
})
useEffect(() => {
handleValidation();
}, [form])
function handleValidation() {
setIsValid(form.password === form.confirm);
}
function onFormValueChanges(event) {
setForm({...form, [event.target.name]: event.target.value})
}
function resetFields() {
setForm({
password: undefined,
confirm: undefined
})
}
function onUpdateClick() {
onChangePassword(form.password);
resetFields();
}
return (
<div className="change-password-container">
<input
type="text"
name="password"
value={form.password}
onChange={(event) => onFormValueChanges(event)}
placeholder="new password" />
<input
type="text"
name="confirm"
value={form.confirm}
onChange={(event) => onFormValueChanges(event)}
placeholder="confirm new password" />
{!isValid ?
<span className="validation-error">passwords do not match</span> : null }
<div className="button-container">
<button onClick={() => resetFields()}>Cancel</button>
<button onClick={() => onUpdateClick()}
disabled={!form.password || !isValid}>Update</button>
</div>
</div>
);
}
export default ChangePasswordComponent;
However when I run the code I get an error in console about...
A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.
When I look back into the documentation, my pattern seems to follow the Docs just fine. Thoughts?
''instead ofundefined.