Search code examples
node.jsreactjsfiltermongoose-schema

How to add filter method onclick button in react


I have a form which has a input field called admissionNumber and the button. In input field when user enter number and click the button then function getAllStudent filter the an array . If admission number match with entered number then other fields (fullname and faculty) automatically filled . How can I do this ? Please someone help me to do this . Thank you

getAllStudents function which return students details (admissionNumber,fullname,faculty)

 getAllStudents(user._id, token).then((data) => {
  if (data.error) {
    setValues({ ...values, error: data.error });
  } else {
    setValues(data);
  }
});

form fields

<input
            type="text"
            onChange={(event) => {
              setSearchTerm(event.target.value);
            }}
            className="form-control offset-md-2  col-md-6"
            placeholder="Admission Number"
            required
            maxLength="5"
          />

          <button
            // onClick={}
            className="btn rounded ml-4"
            
          >
            Verify
          </button>
        </div>
        <div className="bg-dark rounded">Personal Details</div>
        <div className="row form-group ">
          <input
            type="text"         
            name="studentFullName"
            className="form-control mt-2 offset-md-2 col-md-8"
            placeholder="Student Name"
           
          />
          <input
            type="text"
            name="faculty"
            className="form-control mt-2 offset-md-2 col-md-8"
          />
        </div>

enter image description here


Solution

  • You should pass a function to button onClick prop.

    Assuming you using a functional component and a state with students, currentUser and searchTerm you can do something like that:

    const [students] = useState([...])
    
    const [currentUser, setCurrentUser] = useState(undefined)
    
    const [searchTerm, setSearchTerm] = useState(undefined)
    
    
    const checkStudent = () => {
        const match = students.find(student  => student.admissionNumber === searchTerm)
        if(match) {
            setCurrentUser(match)
        }
    }
    
    return (
        <>
            <button
                onClick={() => checkStudent()}
            />
    
            <input
                type="text"         
                name="studentFullName"
                className="form-control mt-2 offset-md-2 col-md-8"
                placeholder="Student Name"
                value={currentUser?.fullname}
            />
        </>
    )