Reputation: 1
Hi i'm newbie learning to code and start with Js, Reactjs. I convert my code from class component to functional component and then my validation stop working. i have looking around but yet to find answer, can someone help? ^^"
export default function AddComment() {
const [formValue, setFormValue] = useState ({
rating: '5',
yourname: '',
comment: '',
})
const {rating, yourname, comment} = formValue
const [isModalOpen, setIsModalOpen] = useState(false)
const [touched, setTouched] = useState({yourname: false})
const handleInputChange = (event) => {
const {name, value} = event.target
setFormValue((prevState) => {
return {
prevState,
[name]:value,
};})
}
const handleBlur = (field) => (evt) => {
setTouched({
touch: {...touched, [field]: true }
})
};
function validate(yourname) {
const errors = {
yourname: ''
};
if (touched.yourname && yourname.length <2)
errors.yourname = 'Your name should be atleast 2 characters';
else if (touched.yourname && yourname.length >= 10)
errors.yourname = 'Your name should be less than 10 characters';
return errors
}
const errors = validate(yourname)
return (
<ModalBody>
<Form onSubmit={handleSubmit}>
<FormGroup row>
<Label htmlFor='yourname' md = {12}>Your Name</Label>
<Col md = {12}>
<Input type= 'text' id= 'yourname' name= 'yourname' value= {yourname}
valid={errors.yourname === ''} invalid= {errors.yourname !== ''}
onBlur= {handleBlur('yourname')} onChange= {handleInputChange}/>
<FormFeedback>{errors.yourname}</FormFeedback>
</Col>
</FormGroup>
</Form>
</ModalBody>
)
}
Upvotes: 0
Views: 35
Reputation: 559
Not sure this will solve your problem, but notice on handleInputChange
you are not spreading the previous state, so the object you're setting state with looks like:
{
prevState: {...the actual previous state},
[name]: ...what you wanted to change
}
Upvotes: 1