React Tutorial

React Home React Intro React Get Started React ES6 - ES6 Classes - ES6 Arrow Functions - ES6 Variables - ES6 Array Methods - ES6 Destucturing - ES6 Spread Operator - ES6 Modules - ES6 Ternary Operator React Render HTML React JSX React Components React Class React Props React Events React Conditionals React Lists React Forms React Router React Memo React CSS Styling

React Hooks

What is a Hook? useState useEffect useContext useRef useReducer useCallback useMemo Custom Hooks

React Redux

What is a Redux? React Redux Example

React Exercises

React Quiz

React Props

“props” stands for properties. It is a special keyword in React which is used for passing data from one component to another.

We already know that components are reusable, and we can use our component multiple times in our application. To understand props, you should have a solid understanding of the components and how data flows inside the components.

Components are just like JavaScript functions. They accept random inputs (called “props”) and return React elements which tell what should be displayed on the screen.

Props are like function arguments in JavaScript and attributes in HTML, use the same syntax as HTML attributes:

"medium" attribute to the School element:

const myelement = <School medium="English" />

The component receives the argument as a props object:

import React from 'react';
  import ReactDOM from 'react-dom';

  function School(props) {
    return <h1>I am a { props.medium}!</h1>;
  }

  const myelement = <School medium="English" />;

  ReactDOM.render(myelement, document.getElementById('root')); 

Output :

How to Pass Data

Props are also pass data from one component to another.

We create new component City And send the "medium" property from the City component to the School component

import React from 'react';
  import ReactDOM from 'react-dom';

  function School(props) {
    return <h2>I am a { props.medium}!</h2>;
  }

  function City() {
    return (
      <>
      <h1>Who lives in my city?</h1>
  	    <School medium="English" />
      </>
    );
  }

  ReactDOM.render(<City />, document.getElementById('root'));
  

Output :


Props can be used to pass any kind of data such as:

  • String
  • Array
  • Integer
  • Boolean
  • Objects or,
  • Functions

Why are Props useful?

  • Props provide a medium so that components can talk to each other. In fact, we can reduce thousands of lines of code just by using Props!
  • Whenever we declare any component it can be either a class component or a function component. One thing to notice here is, no matter what kind of component is, it should never change its props value.
  • Hence the components should act like pure functions (which can’t change their own input) to their props.
  • But, if you really want to change or introduce some dynamic UIs that should change within the component, you should learn about “State”.

React State

State is a plain JavaScript object used by React to represent an information about the component’s current situation.

It’s managed in the component (just like any variable declared in a function)

State allows React components to change their values over time without any violations. A state is usually called as an encapsulated one or having a local scope of the component.

Components defined as classes have some additional features. Local state is exactly that: a feature available only to classes. State can only be used within a class and usually the only place where you can assign this.state is the constructor.

Creating the state Object

The state object is initialized in the constructor. Specify the state object in the constructor method:

class School extends React.Component {
  constructor(props) {
    super(props);
    this.state = {medium: "English"};
  }
  render() {
    return (
      <div>
      <h1>My School</h1>
      </div>
    );
  }
}

state object can contain as many properties

class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "multigrey",
        year: 1884
      };
    }
    render() {
      return (
        <div>
          <h1>My School</h1>
        </div>
      );
    }
  }

Use of state Object in React App

Refer to the state object anywhere in the component by using the this.state.propertyname syntax:

 import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "multigrey",
        year: 1884
      };
    }

    render() {
      return (
        <div>
        <h1>My {this.state.medium}</h1>
          <p>
            It is a {this.state.color}
            {this.state.board}
            board school from {this.state.year}.
          </p>
        </div>
      );
    }
  }

  ReactDOM.render(<School />, document.getElementById('root'));

Output :

Always use the setState() method to change the state object, it will ensure that the component knows its been updated and calls the render() method (and all the other lifecycle methods).

When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s)

Add a button with an onClick event that will change the color propert


  import React from 'react';
  import ReactDOM from 'react-dom';

  class School extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        medium: "English",
        board: "CBSE",
        color: "multigrey",
        year: 1884
      };
    }
    changeColor = () => {
      this.setState({color: "Black"});
    }
    render() {
      return (
        <div>
        <h1>My {this.state.medium}</h1>
          <p>
            It is a {this.state.color}
            {this.state.board}
            board school from {this.state.year}.
          </p>
          <button type="button"onClick={this.changeColor}
        >Change color</button>
          </div>
      );
    }
  }

  ReactDOM.render(<School />, document.getElementById('root')); 

Output :


What are the differences between props and state?

take a look at some high-level differences between state and props. Although they do similar things, they are used differently.

While both are used for data manipulation, one is of private and the other is of dynamic context.

  • Props are used to pass data from parent to child whereas the state is used for data manipulation inside the component.
  • We can get the value of props from the parent component, where we get the value of state object from the initial data defined in the constructor() method
  • While this.props is set up by React itself, with this.state we are free to add additional fields to the component manually to store something or in a scenario that doesn’t participate in the data flow.
  • Props are immutable, i.e We can't change props passed to a component whereas we can change the State, i.e React uses the setState() method to update the object of a state (but within the component itself)

To learn more about Click Events go to next chapter.