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>
    );
  }






Friday, December 6, 2019

React Components | What is Component in React Js | Importance of Components in Application

Hello & As-salam u alikum ! This is the second article related to React js , In this blog we will discuss the introduction and importance of Components.

The Programmers used to write a lot of code in earlier days to create application ,In which many of the code was much repetitive ,assume that there is one functionality which is present on page-1 ,page-2 ,page-3 & pages-4 ,we use to copy and paste the code on each page, when ever any change was required,we need to change the code on every page or view, That was very difficult task for developer for manage such code. 

React js came to resolve this problem with component base class code. In which we do not have to write the code again and again ,we just make a single unit of generic code once then we use the same component every where on application. 





Types of Components: 

React js have two types of components
  1. Functional 
  2. Class
In ReactJS, we have mainly two types of components. They are
  1. Functional Components
  2. Class Components

Functional Components:

function components are a way to write components that only contain a render method and don't have their own state. They are simply JavaScript functions that may or may not receive data as parameters. We can create a function that takes props(properties) as input and returns what should be rendered. A valid functional component can be shown in the below example.

Example

  1. import React, { Component } from 'react';  
  2. class App extends React.Component {  
  3.    render() {  
  4.       return (  
  5.          <div>  
  6.             <Title />  
  7.             <Description/>  
  8.          </div>  
  9.       );  
  10.    }  
  11. }  
  12. class Title extends React.Component {  
  13.    render() {  
  14.       return (  
  15.          <div>  
  16.             <h1>Dot Net Core Community</h1>  
  17.          </div>  
  18.       );  
  19.    }  
  20. }  
  21. class Description extends React.Component {  
  22.    render() {  
  23.       return (  
  24.          <div>  
  25.             <a href="https://dotnetcorecommunity.blogspot.com/"> our Blog</a>  
  26.             <p>MY NAME IS SALMAN MASOOD , I M A COMPUTER SCIENCE & MATHS GRADUATED FROM UNIVERSITY OF KARACHI, PAKISTAN , TEACHING IS MY PASSION AND MY AIM IS TO DELIVER ALL MY KNOWLEDGE AMONG THOSE STUDENTS WHO CAN'T AFFORD TUTORS OR EXPENSIVE INSTITUTE FEES. TILL MY LAST BREATH  I WILL BE KEEP SHARING MY ALL KNOWLEDGE AND INFORMATION WITH YOU .... KEEP REMEMBER ME IN YOUR PRAYERS !   </p>  
  27.          </div>  
  28.       );  
  29.    }  
  30. }  
  31. export default App;  


Class Components:

Class components are more complex than functional components. It requires you to extend from React. Component and create a render function which returns a React element. You can pass data from one class to other class components. You can create a class by defining a class that extends Component and has a render function.




  1. 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"
            }
          ]
        };
      }

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

            <StudentName />

            <List data={this.state.data} />
          </div>
        );
      }
    }
    class StudentName extends React.Component {
      render() {
        return (
          <div>
            <h1>Student Name Detail</h1>
          </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;