Search code examples
javascriptreactjsreact-componentreact-lifecycle

How to handle the props from Parent Component to child component to populate props data in the form for updation


I want to edit the guest data of my app. Why I click the edit button I take the ID, send it to GUEST class component and there I get the data from the state and then I send it to the input component (GuestForm). The problem is I am able to get the edit data in GuestForm component but I want to set the state somehow...so that I can see the data to be edited in the form pre-populated. Please help me I am new to React. I tried searching for different lifecycle methods but can't find any. After this I will use componentDidUpdate() to handle the update data. But please help me to populate the data from props to the form.

I am using Class Component. So please help me in this regard only.

Here is my Code index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Guest Register</title>
    <!--BOOTSTRAP, FONTAWESOME CDN-->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.css"
      integrity="sha256-46qynGAkLSFpVbEBog43gvNhfrOj+BmwXdxFgVK/Kvc="
      crossorigin="anonymous"
    />
    <!--END-->
  </head>
  <body class="bg-white">
    <!--ROOT ELEMENT-->
    <div id="root"></div>
    <!--END OF ROOT ELEMENT-->

    <!--REACT,REACT-DOM, BABEL CONFIG CDN-->
    <script
      crossorigin
      src="https://unpkg.com/react@16/umd/react.development.js"
    ></script>
    <script
      crossorigin
      src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"
    ></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <!--END OF CONFIG CDN-->

    <!--APPLICATION MAIN CODE-->
    <script src="App.js" type="text/babel"></script>
    <!--APPLICATION CODE END-->
  </body>
</html>

Here is my App.js

class GuestForm extends React.Component {
  state = {
    name: "",
    guestType: "",
    isEdit: false
  };

  changeName(name) {
    this.setState({
      name: name
    });
  }

  changeGuestType(type) {
    this.setState({
      guestType: type
    });
  }

  submitForm() {
    this.props.getGuestData(this.state);
    this.setState({
      name: "",
      guestType: ""
    });
  }

  componentDidUpdate = (prevProp, newProp) => {
    console.log("CDU: ", prevProp, newProp);
  };

  render() {
    return (
      <form>
        <div className="form-group">
          <input
            type="text"
            className="form-control"
            placeholder="Guest Name"
            value={
              this.props.dataToEdit.name
                ? this.props.dataToEdit.name
                : this.state.name
            } //value attribute doesn't works here
            onChange={event => this.changeName(event.target.value)}
            required
          />
        </div>
        <div className="form-group">
          <select
            className="form-control"
            value={
              this.props.dataToEdit.guestType
                ? this.props.dataToEdit.guestType
                : this.state.guestType
            }
            onChange={event => this.changeGuestType(event.target.value)}
            required
          >
            <option value="">Choose Type</option>
            <option value="VIP">VIP</option>
            <option value="NORMAL">Normal</option>
            <option value="CHIEF GUEST">Chief Guest</option>
          </select>
        </div>
        <button
          onClick={e => {
            e.preventDefault();
            this.submitForm();
          }}
          className="btn btn-primary"
        >
          {this.props.dataToEdit.isEdit ? "UPDATE" : "ADD"}
        </button>
      </form>
    );
  }
}

class GuestList extends React.Component {
  guestToDelete(id) {
    this.props.getTheIdToDelete(id);
  }
  guestToEdit(id) {
    this.props.getTheIdToEdit(id);
  }
  render() {
    return (
      <tr key={this.props.index}>
        <td scope="row">{this.props.name}</td>
        <td>{this.props.guestType}</td>
        <td>
          <a onClick={() => this.guestToEdit(this.props.index)}>
            <i className="far fa-edit text-info"></i>
          </a>
          &nbsp;&nbsp;
          <a onClick={() => this.guestToDelete(this.props.index)}>
            <i className="fa fa-trash-alt text-danger"></i>
          </a>
        </td>
      </tr>
    );
  }
}

class Guest extends React.Component {
  state = {
    guests: [],
    editGuestdata: []
  };

  getFormDataForGuests(data) {
    if (data.name && data.guestType) {
      this.setState(
        {
          guests: [...this.state.guests, data]
        },
        () => {
          console.log("GUEST:", this.state);
        }
      );
    }
  }

  guestToDelete(id) {
    let updatedGuest = [...this.state.guests];
    updatedGuest.splice(id, 1);
    this.setState({
      guests: updatedGuest
    });
  }

  guestToEdit(id) {
    let editData = {
      name: this.state.guests[id].name,
      guestType: this.state.guests[id].guestType,
      isEdit: true
    };
    this.setState({
      editGuestdata: editData
    });
  }

  render() {
    return (
      <div className="row text-center m-2">
        <div className="col-md-5 card mx-auto shadow m-1 p-3 col-xs-10">
          <h3>Guest Form</h3>
          <GuestForm
            dataToEdit={this.state.editGuestdata}
            getGuestData={data => this.getFormDataForGuests(data)}
          />
        </div>
        <div className="col-md-5 card mx-auto m-1 p-3 shadow col-xs-10">
          <table className="table table-striped">
            <thead>
              <tr>
                <th>Name</th>
                <th>Guest Type</th>
                <th>Edit/Delete</th>
              </tr>
            </thead>
            <tbody>
              {this.state.guests.map((data, index) => {
                return (
                  <GuestList
                    getTheIdToDelete={id => this.guestToDelete(id)}
                    getTheIdToEdit={id => this.guestToEdit(id)}
                    index={index}
                    name={data.name}
                    guestType={data.guestType}
                  />
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
    );
  }
}

ReactDOM.render(<Guest />, document.getElementById("root"));


Solution

  • Try accessing the values from 'dataToEdit' in the form component.

    <input
       type="text"
       className="form-control"
       placeholder="Guest Name"
       value={this.props.dataToEdit.name} //this will pull in as props not state
       onChange={event => this.changeName(event.target.value)}
       required
    />
    

    If it is still not working then the dataToEdit is not being set properly.