Search code examples
javascriptreactjsreact-hooksreact-forms

Facing a problem while Handle an input with React hooks


I try to handle the user's text input with hooks.

 const [inputValues, setInputValues] = useState({
firstName:"",
lastName:"",
email:"",
telNum:"",
contactType:"Tel.",
message:"",
agree:false

});

and I try to update the values by

  const handleChange = event => {
setInputValues({ ...inputValues, [event.target.name]: event.target.value,});
}

and the event:

onChange={handleChange}   

Sample input Field code:

    <FormGroup row>
          <Label htmlFor='firstname' md={2}>
            First Name
          </Label>
          <Col md={10}>
            <Input
              type='text'
              id='firstname'
              name='firstname'
              placeholder='First Name'
              value={firstName}
              valid={errors.firstName === ""}
              invalid={errors.firstName !== ""}
              onBlur={handleBlur("firstName")}
              onChange={handleChange}             />
            <FormFeedback>{errors.firstName}</FormFeedback>
          </Col>
        </FormGroup>

But whenever I typed something in the input field. I Can't find the value that I entered un the input field. I didn't understand what happened here. Please Help me to get out from this


Solution

  • There is a typo error in your code. name property is firstName not firstname.

    <FormGroup row>
              <Label htmlFor='firstname' md={2}>
                First Name
              </Label>
              <Col md={10}>
                <Input
                  type='text'
                  id='firstname'
                  name='firstName'
                  placeholder='First Name'
                  value={inputValues.firstName}
                  valid={errors.firstName === ""}
                  invalid={errors.firstName !== ""}
                  onBlur={handleBlur("firstName")}
                  onChange={handleChange}             />
                <FormFeedback>{errors.firstName}</FormFeedback>
              </Col>
            </FormGroup>