Home > Net >  How to store input values of a form in a array to print array data in table list in Reactjs
How to store input values of a form in a array to print array data in table list in Reactjs

Time:12-15

I have a form with three input field which I clone and remove on click and when I submit form it's value show in a table.

Issues: after submitting value it shown in table but if I add another field and type it directly updating my table without submitting.

Table should update only after submit value. Also please suggest how can make this form better.

import { useState } from "react";

export default function Form() {

  const [input, setInput] = useState([{ firstName: "" , lastName: "", email: ""} ]);
  const [view, setView] = useState("Hide");
 
  let getValue = (i, e) => {
    let newInput = [...input];
    newInput[i][e.target.name] = e.target.value;
    setInput(newInput);
  }
  let addFormFields = () => {
    setInput([...input, { firstName: "" , lastName: "", email: ""}])
  }

  let removeFormFields = (i) => {
    let newInput = [...input];
    newInput.splice(i, 1);
    setInput(newInput);
  }

    let formSubmit = (event) => {
      event.preventDefault();
      setView("Show")

    }

  return (
    <>
    <div className='form-box'>

      <form onSubmit={formSubmit} >

        {input.map((element, index) => (
          <div className="form" key={index}>
          
            <label>First Name</label>
           <input type="text" name="firstName" value={element.firstName || ""} onChange={(e) => getValue(index, e)}
            />
            <label>Last Name</label>
           <input type="text" name="lastName" value={element.lastName || ""} onChange={(e) => getValue(index, e)}
            />
            <label>Email</label>
            <input type="email" name="email" value={element.email || ""} onChange={(e) => getValue(index, e)}
            />
            {index ? (
              <button
                type="button"
                className="btn-danger btn-sm mt-2 "
                onClick={() => removeFormFields(index)}
              >
                Remove
              </button>
            ) : null}
          </div>
        ))}
          <button
            className="btn btn-info m-2"
            type="button"
            onClick={() => addFormFields()}
          > Add</button>
          <button className="btn btn-success m-2" type="submit">
            Submit
          </button>
      </form>
      </div>
      {view === "Show" ? <Table TableData={input}/> : null}
      </>
  )
}

function Table(props) {
  return (
    <div>
      <div >
        <table >
          <thead>
            <tr>
              <th scope="col">First Name</th>
              <th scope="col">Last Name </th>
              <th scope="col">Email</th>
            </tr>
          </thead>
          <tbody>
            {props.TableData.map((list) => {
              return (
                <tr>
                  <td>{list.firstName}</td>
                  <td>{list.lastName}</td>
                  <td>{list.email}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

enter image description here

CodePudding user response:

Issues: after submitting value it shown in table but if I add another field and type it directly updating my table without submitting. it's not your issue, actually changing in form always updates table immediately , but since in the first render view state is equal to Hide actually you never render table, if you change it you can see that when you type something in the first form, it immediately updates the table. To solve the proble you can separate table's data and form's data, I implemented a simple example Here. You can check it out.

CodePudding user response:

As you are using same input array to display table value and input value, when input data changes table data changes with it. I would recommend adding one more state object for table value.

import React, { useState } from "react";

export default function Form() {
  const [input, setInput] = useState([{ firstName: "" , lastName: "", email: ""} ]);
  const [tableValue, setTableValue] = useState([]);
  const [view, setView] = useState("Hide");
 
  let getValue = (i, e) => {
    ...
  }
  let addFormFields = () => {
    ...
  }

  let removeFormFields = (i) => {
    ...
  }

  let formSubmit = (event) => {
    event.preventDefault();
    let arr = [];
    for(let i in input) {
      arr.push({...input[i]})
    }
    setTableValue(arr)
    setView("Show")
  }

  return (
    <>
    <div className='form-box'>
      <form onSubmit={formSubmit} >
        ...
      </form>
    </div>

    {view === "Show" ? <Table TableData={tableValue}/> : null}
    </>
  )
}

function Table(props) {
  ...
}

  • Related