Tuesday, December 10, 2019

Reat State| Maintaining State in React js | Adding New Records in Json Object

Hello & As-salam u alikum ! This is the 3rd article related to React js , In this blog we will discuss about the State in React js which is the backbone of react applications, Lets do it!

In the previous article, we had discuss about the functional and class components, now we will use a class component to display records from current state and we will add new records in the json object or state of the component.

Below is the complete code for your application, I explain all these line of code partially.

import React, { Component } from "react";

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      data: [
        {
          id: 1,
          name: "salman"
        },
        {
          id: 2,
          name: "Raza"
        },
        {
          id: 3,
          name: "Muzammil"
        }
      ],
      sname: ""
    };
  }

  submitForm(e) {
    const getMax = (arrprop=> {
      var max;
      for (var i = 0i < arr.lengthi++) {
        if (!max || parseInt(arr[i][prop]) > parseInt(max[prop])) max = arr[i];
      }
      return max;
    };

    e.preventDefault();
    var maxid = getMax(this.state.data"id");
    console.log(maxid.id);
    this.setState(prevState => {
      return {
        data: [...prevState.data, { id: maxid.id + 1name: this.state.sname }],
        sname: ""
      };
    });
    e.target.reset();
  }

  textchange(e) {
    this.setState({ [e.target.name]: e.target.value });
    //what ever you write ,it changes the state

    // console.log(e.target.value);
  }

  render() {
    return (
      <div className="Container">
        
       

        <div className="Container">
          <form onSubmit={this.submitForm.bind(this)}>
            <div className="form-group">
              <input
                type="text"
                name="sname"
                required
                onChange={this.textchange.bind(this)}
                style={marginTop: "30px" }}
                placeholder="Enter Post Title........"
                className="form-control"
              />
            </div>

            <div className="form-group">
              <button
                style={width: "280px" }}
                type="submit"
                className="btn btn-primary "
              >
                Post
              </button>
            </div>
          </form>
        </div>
      

        <List data={this.state.data} />
      </div>
    );
  }
}

class List extends React.Component {
  render() {
    return (
      <table className="table">
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {this.props.data.map(item => (
            <tr key={item.id}>
              <td>{item.id}</td>

              <td>{item.name}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}
export default App;


Step# 1:  First we will create a functional component named as List which will display the records present in the json or state of our main component i.e "App" Component. you may notice that data is displaying through map method ,and the data source is a "props" or a property named as data. we will supply value to this property in "App" Component.
class List extends React.Component {
  render() {
    return (
      <table className="table">
        <thead>
          <tr>
            <th>id</th>
            <th>Name</th>
          </tr>
        </thead>
        <tbody>
          {this.props.data.map(item => (
            <tr key={item.id}>
              <td>{item.id}</td>

              <td>{item.name}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}
Step# 2:  Now we will add Constructor in App Component ,which will contain the initialized data .

 constructor() {
    super();

    this.state = {
      data: [
        {
          id: 1,
          name: "salman"
        },
        {
          id: 2,
          name: "Raza"
        },
        {
          id: 3,
          name: "Muzammil"
        }
      ],
      sname: ""
    };
  }


Step# 3:  Add the submit event ,which contains the code for adding new records in state.

  submitForm(e) {
    const getMax = (arrprop=> {
      var max;
      for (var i = 0i < arr.lengthi++) {
        if (!max || parseInt(arr[i][prop]) > parseInt(max[prop])) max = arr[i];
      }
      return max;
    };

    e.preventDefault();
    var maxid = getMax(this.state.data"id");
    console.log(maxid.id);
    this.setState(prevState => {
      return {
        data: [...prevState.data, { id: maxid.id + 1name: this.state.sname }],
        sname: ""
      };
    });
    e.target.reset();
  }
Step# 4:  Add the text change event ,which will hold the value of input text value in text box.
textchange(e) {
    this.setState({ [e.target.name]: e.target.value });
    //what ever you write ,it changes the state

    // console.log(e.target.value);
  }
Step# 5:  Add the render method to display the HTML on view . this method is containing everything which is to be displayed on view.

 render() {
    return (
      <div className="Container">
       

        <div className="Container">
          <form onSubmit={this.submitForm.bind(this)}>
            <div className="form-group">
              <input
                type="text"
                name="sname"
                required
                onChange={this.textchange.bind(this)}
                style={marginTop: "30px" }}
                placeholder="Enter Post Title........"
                className="form-control"
              />
            </div>

            <div className="form-group">
              <button
                style={width: "280px" }}
                type="submit"
                className="btn btn-primary "
              >
                Post
              </button>
            </div>
          </form>
        </div>
        <StudentName />

        <List data={this.state.data} />
      </div>
    );
  }






1 Comments:

At January 17, 2020 at 2:55 PM , Blogger MS Dynamics said...

Very good explanation. Thank you for sharing.
React JS Online training

React JS training in hyderabad

 

Post a Comment

Do not Add Spam links in the Comment Box

Subscribe to Post Comments [Atom]

<< Home