Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to create forms in react?

I am beginner in react. I have following code:

import React, { useState, useEffect } from 'react';
import { Card, Form, Button } from 'react-bootstrap';
import Axios from 'axios'

export function StudentForm({ student, onSuccess, onError, setState }) {
    const url = `http://localhost:9899/api/StudentData`;

    const intialStudent = { Firstname: '', Middlename: '', Lastname: '', DOB: '', Gender: '' };

    const [Student, setStudent] = useState(intialStudent);

    useEffect(() => {
        setStudent(student ? student : intialStudent);
    }, [student]);

    const SaveData = function (studentData) {

        if (student._id) {
            Axios.post(url, { ...studentData }, { headers: { 'accept': 'application/json' } })
                .then(res => {
                    setState(null);
                    onSuccess(res);

                })
                .catch(error => {
                    alert('Error To Edit data');
                });
        }
        else {
            Axios.post(url, studentData, { headers: { 'accept': 'application/json' } })
                .then(res => {
                    setState(null);
                    onSuccess(res);
                })
                .catch(err => onError(err));
        }
    }
    return (
        <Card>
            <Card.Header><h5>{student ? "Edit" : "Add"} Student</h5></Card.Header>
            <Card.Body>
                <Form onSubmit={(e) => { e.preventDefault(); SaveData(Student); }}>
                    <Form.Group><Form.Control type="text" name="Firstname" placeholder="Firstname" value={Student.Firstname} onChange={e => { setStudent({ ...Student, Firstname: e.target.value }) }} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Middlename" placeholder="Middlename" value={Student.Middlename} onChange={e => setStudent({ ...Student, Middlename: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Lastname" placeholder="Lastname" value={Student.Lastname} onChange={e => setStudent({ ...Student, Lastname: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="date" name="DOB" placeholder="DOB" value={Student.DOB} onChange={e => setStudent({ ...Student, DOB: e.target.value })} /></Form.Group>
                    <Form.Group><Form.Control type="text" name="Gender" placeholder="Class" value={Student.Gender} onChange={e => setStudent({ ...Student, Gender: e.target.value })} /></Form.Group>
                    <Button variant="primary" type="submit">Submit</Button>
                </Form>
            </Card.Body>
        </Card>
    );
}

In above code I am setting state on change event on each field. So it will render again and again when I change any of the field.If it is large form so it may take a lot of time to re-render so is there a better way to create to handle this kind of situation, or any best practices for using forms with react?

like image 333
rushang panchal Avatar asked Nov 17 '25 11:11

rushang panchal


2 Answers

Managing forms in react is a task complex enough to delegate it to a library. Alo, big forms are not a good candidate for functional components because the problems that you outlined. You can, of course, spend the time to tune it up, but I think the effort may not worth the benefit.

My personal recommendation is to try one of the many react form libraries out there. One that I personally like is Formik

If you want to manage the form yourself I recommend to encapsulate the form on stateful component and use the key property for easier reset when you need it.

Another alternative will be the usage of memoization, for example using react.memo. But that will not guarantee success unless your data has the proper shape. This means, simple values that can be compared between themselves, not arrays, not functions, not objects.

like image 79
Danielo515 Avatar answered Nov 19 '25 01:11

Danielo515


You can use only one Function for all onChanges. Looks like this;

<Form.Group>
  <Form.Control
     type="text"
     name="Firstname"
     placeholder="Firstname"
     value={Student.Firstname}
     onChange={handleChange} 
  />
</Form.Group>

And this is your handleChange function;

const handleChange = e => {
  const {name, value} = e.target
  setValues({...values, [name]: value})
}

This is your state;

const [values, setValues] = useState({
  Firstname: "", 
  Middlename: "", 
  Lastname: "",
  DOB: "",
  Gender: ""
})

I think this way is more effective with less code.

like image 38
MehmetDemiray Avatar answered Nov 18 '25 23:11

MehmetDemiray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!