ReactJS – Props

When React finds an element representing a user-defined component, it passes JSX attributes to this component as a single object, and this object is called “Props”.

Props are arguments nothing else that are passed into React components.

Let us understand with an example

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

function Tutorial(props){
            <h1> Learn Online {props.tutorial_name}</h1>
            <h1>I am learning it from {props.tutorial_site}.</h1>

ReactDOM.render(<Tutorial tutorial_name="ReactJS" tutorial_site="Share Query" />, document.getElementById("root"));

In the above example, please look at the last line :

  • tutorial_name and tutorial_site are the JSX attributes
  • Tutorial is the react component to which these JSX attributes are passed
  • And when react sees the user defined component having JSX attributes, then it passes these JSX attributes to a single object which is called “props”

So you can consider props will might be similar as below object format:

props = {tutorial_name:”ReactJS”, tutorial_site:”Share Query”}

Whether you declare a component as a function or a class, it must not modify its own props value. props value remains immutable throughout the function or class returns. All react components must act like pure functions with respect to their props.

Pure function means

function add(a,b)
	return a+b;

Impure function means

function withdraw(account, amount)
{ -= amount;

Props in the Constructor

If you are using constructor function inside component, the props should always be passed to the constructor and also to the React.Component by the super() method.

Trending Topics