Search code examples
reactjswebreact-hooksmernreact-fullstack

Why I'm unable to fill the input fields using react use State hook?


import React from "react";
import "./App.css";
import { useForm } from "react-hook-form"; 
import classNames from "classnames";
import { useState } from "react";


function App() {
      const { register, handleSubmit,formState: { errors } } = useForm();
      console.log(errors);
      const onSubmit = data => console.log(data);

Here i use useState hook First I use only one state for all fields

  const [userData,setUserData] = useState({
    userName:"",
    CNIC:"",
    number:"",
    email:"",
    Car_Name:"",
    Car_Model:"",
    Car_Color:"",
    Brand_Name:"",
    Address:"",

  });

Then store it Dynamically for every field

  let name,value;

  const postUserData = (event) => {
    name = event.traget.name;
    value = event.traget.value;

Even I update it through setUserData.But still it not working And here I Update it for every field dynamically.But not updating??

     setUserData({...userData,[name]:value});

  };
  
  return (
<div>

There are the some fields

<div className="container">
      <br />
      <h1 className="text-center text-success">Form validation in React</h1>
      <br />
      <div className="form-group my-3 ">
        <form name="Registration_form" id="Form" action="" onSubmit={handleSubmit(onSubmit)}>
          
          <div className="form-group my-3">
            <label htmlFor="name">Name:<span style={{fontWeight:"bold",color:"red"}}>*</span></label>
           
            <input 
              type="text" 
              name="userName" 
              id="Name" 
              value={userData.userName}
              onChange={postUserData}
              className={classNames("form-control",{"is-invalid":errors.Name,})}  
              autoComplete="off" 
              {...register('Name', 
              { required: true,
                maxLength: 15,
                pattern: /^[A-Za-z]+$/
              
              })
              }

              
              />

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "required"  && "This field is required"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type ==="maxLength" && "Length Should be less then 15"}</span>

            <span id="name" className="text-danger fw-bold">{errors.Name?.type === "pattern"  && "Digits are not allow"}</span>

          </div>
          <div className="form-group my-3">
            <label htmlFor="CNIC">CNIC:<span style={{fontWeight:"bold",color:"red"}}>*</span></label>
            
            <input 
              type="text" 
              name="CNIC" 
              id="CNIC"
              value={userData.CNIC}
              onChange={postUserData} 
              className={classNames("form-control",{"is-invalid":errors.CNIC,})}  
              placeholder="XXXXX-XXXXXXX-X" 
              autoComplete="off"
              {...register('CNIC', 
              { 
                required: true,
                minLength:15,
                maxLength:15,
                pattern:/[0-9]/g,
                validate: {
                  format: (value) => /^[0-9]{5}[-]{1}[0-9]{7}[-]{1}[0-9]{1}$/.test(value)
                }
              })
              } 
            
              />

            <span id="cnic" className="text-danger fw-bold">{errors.CNIC?.type === "required"  && "CNIC is required"}</span>

            <span id="cnic" className="text-danger fw-bold">{errors.CNIC?.type ==="minLength" && "Length must be equal to 15"}</span>

            <span id="cnic" className="text-danger fw-bold">{errors.CNIC?.type ==="maxLength" && "Length must be equal to 15"}</span>

            <span id="cnic" className="text-danger fw-bold">{errors.CNIC?.type === "pattern"  && "Charaters are not allow"}</span>

            <span id="cnic" className="text-danger fw-bold">{errors.CNIC?.type === "format"  && "Invalid format"}</span>

            
          </div>
          <div className="form-group my-3">
            <label htmlFor="number">Mobile Number:<span style={{fontWeight:"bold",color:"red"}}>*</span> </label>
            
            <input 
             type="text" 
             name="number" 
             id="number" 
             value={userData.number}
              onChange={postUserData} 
             className={classNames("form-control",{"is-invalid":errors.number,})}  
             placeholder="XXXX-XXXXXXX" 
             autoComplete="off" 
             {...register('number', 
              { 
                required: true,
                pattern:/[0-9]/g,
                validate: {
                  format: (value) => /^((\+92)?(0092)?(92)?(0)?)(3)([0-9]{2})((-?)|( ?))([0-9]{7})$/gm.test(value)
                }
                // /^((\+92)?(0092)?(92)?(0)?)(3)([0-9]{2})((-?)|( ?))([0-9]{7})$/gm

              
              })
              }
            
             />

              <span id="number" className="text-danger fw-bold">{errors.number?.type === "required"  && "Number is required"}</span>

              <span id="number" className="text-danger fw-bold">{errors.number?.type === "pattern"  &&"Charaters are not allow"}</span>

              <span id="number" className="text-danger fw-bold">{errors.number?.type === "format"  && "Invalid format"}</span>

          </div>

This is some fields can anyone check the mistake why i am unable to fill the fields??


Solution

  • Why you are using state together with react-hook-form?

    The whole purpose of this library is to use uncontrolled inputs.

    Did you check what exacly register(...) gives you? There is onChange that overrides your onChange.

    No need to use state when you are using react-hook-form