What Are React.Js Prop

Read it in 10 Mins

Last updated on
07th Jun, 2022
Published
01st Oct, 2020
Views
10,179
What Are React.Js Prop

Understanding data manipulation in React is never an easy job. React has a unidirectional data flow due to which the technique of data manipulation in React is slightly different than in other frameworks.   

To understand the concepts like Props or State, I’d recommend you brush up or go through the data flow concepts in React first. Also, you can click here to know more about usereducer hooks in React. 

In this article, we’re going to focus only on the Props feature and how to use it in React. 

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.  

If you don’t know much about React components, I recommend you stop here and read about React components first before continuing! 

Let’s now learn what are “props” and how to use them?

What is Props in React?   

We all know that React Components allow you to split the application interfaces into reusable, independent segments.
 
“Props” stands for properties. It is a special keyword in React which is used for passing data from one component to another.
 
Logically, 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 can be used to pass any kind of data such as:  

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

Understanding ReactJS Props   

We are all quite familiar with parent and child components.

If you aren’t, then before delving deep into 
ReactJS props, it’s important to revisit concepts on parent and child components.

class ParentComponent extends Component {   
render() { 
   return ( 
     < h1 > 
       I'm the big parent component. 
       <ChildComponent /> 
     </ h1 > 
   ); 
} 
}

And here is the child component:

const ChildComponent = () => {   
return <p>I'm a small child!</p>
};

And did you realize that when we called the child component inside the parent component, we end up rendering the same data again and again?

The problem we want to solve here is, we want to render the dynamic data and not static data!

Let’s understand this with a simple example. Here we have two components:    

One is the parent component which is a class component:

//this is Parent component 

import React, { Component } from 'react'; 
import MyComponent from './MyComponent.jsx'; 
class App extends Component { 
   render() { 
       return ( 
           <div> 
               <MyComponent /> 
               <MyComponent /> 
           < /div> 
       ); 
   } 
} 
export default App;

And we are rendering the child component ( MyComponent ) which is a functional component inside the parent as follows:

import React from 'react'; 
const MyComponent = () => { 
   return < h1 > Hello Michael </h1> 
} 
export default MyComponent;

The result will be like this:

Hello Michael 
Hello Michael

This is coming twice, because we have used <MyComponent> twice in our parent component. We can re-use this component any ‘n’ number of times as we want.

Now, what if a certain scenario demands that we don’t require this static data in the child component, and we want some dynamic data when the component renders? What I meant is that I want to reuse the child component not with the data it has, but with some other data like:

Hello Michael 
Hello Professor

Here we can make use of Props or properties. We can add props in the component in the same way that we add attributes in our HTML.

Let’s add Props in our older component and see the results:  

import React, { Component } from 'react'; 
import MyComponent from './MyComponent.jsx'; 
class App extends Component { 
   render() { 
       return ( 
           <div> 
               <MyComponent name = "Michael" /> 
               <MyComponent name = "Professor" /> 
           </div> 
       ); 
   } 
} 
export default App;  

In the above file, we have used a name attribute with the desired dynamic value we want after rendering the data. Now, the most important point here is to pass props to the child component.

Passing Props >>>>>  

import React from 'react'; 
const MyComponent = (props) => { 
   return < h1 > {props.name} </ h1> 
} 
export default MyComponent;  

If you try to console the value of Props, you will see nothing but a plain JavaScript object with key-value pairs. We can access the value as key of “name” using (.) dot notation like this >>> “props.name“,  

In the final step, we have used interpolation to use the props and we enclose it in curly brackets because it is a JSX expression.  

Now after calling the child component inside the parent component, here comes the desired output which is

Hello Michael 
Hello Professor 

Now that we’ve successfully rendered the data of the child component from the parent component, let’s dig deeper!

Props in the Constructor:

In the above example, we have used a functional component.   

What if we have a class component and we want to use props in that component?  

Normally, a constructor() method is invoked when a class in a component is created without using the newer public class fields syntax. Most of the times when a constructor() is invoked, the super() method is invoked inside of it. Otherwise, the parent’s constructor will not be executed.  

See the snippet below for the class component:  

class MyComponent extends React.Component { 
   constructor(props) { 
       super(props); 
       console.log(this.props); // props will be logged here. 
   } 
   render() { 
       return < h1 >Hello {this.props.name}</h1>;    } 
}  

To access the props we use this.props.  

To summarize the above: If we want to use this.props inside the constructor, we need to pass it in super, or else we can use it in render() without using super()  

Using Props in React & Passing Data using Props  

Props are mainly used for passing data from the parent component to child component. It motivates us to reuse the components and reduce redundancy as well. But as a growing app, you might see a lot of bugs with typechecking.  

In React there is a special inbuilt feature that is used to check the basic validations during typechecking using PropTypes.  

See the depth and power of propTypes here:  

import PropTypes from 'prop-types' 
export default class Mycomponent extends React.Component { 
   render() { 
       // .... Your code goes here 
   } 
} 
Heading.propTypes = { 
   content: PropTypes.string.isRequired, 
   message: PropTypes.array.isRequired, 
   onClickPropTypes.func.isRequired, 
   length: PropTypes.number.isRequired, 
   styles: PropTypes.object.isRequired, 
   isReadyPropTypes.bool.isRequired 
} 

PropTypes, a built-in-type checker, ensures that the right type of props is passed to a component. We can define components without propTypes as well, but why risk our application with any wrong data type that might lead to a crash?  

NOTE: propTypes can only be checked in development mode (for performance reasons) 

PROPTYPES exports a huge range of validators which can be used to make sure that the data you receive is checked and valid, completely bug free!   

To use typechecking on the props for a component, let’s use and assign the special propTypes property as follows:   

import PropTypes from 'prop-types'; 
class MyComponent extends React.Component { 
   render() { 
       return ( 
           < h1 >Hello, {this.props.name}</h1> 
       ); 
   } 
} 
 
MyComponent.propTypes = { 
   name: PropTypes.string 
};  

In this example, we have used “PropTypes.string”. When an invalid value is provided for a prop, for-ex, other than a string, a warning will be thrown in the JavaScript console. To learn more about prop types, head over here  

Default Props

There could be certain scenarios in which we need some default props so that props are set even if a parent component doesn’t pass the props down. 

In this case, we can also define default values for the props directly to the constructor by assigning to the special property known as defaultProps provided by React.  

class MyComponent extends React.Component { 
   render() { 
       return ( 
           < h1 >Here comes the, {this.props.name}</h1> 
       ); 
   } 
} 
 
// Specifies the default values for props: 
MyComponent.defaultProps = { 
   name: 'new value' 
}; 
 
// Renders "Here comes, new value": 
ReactDOM.render( 
   <MyComponent />, 
   document.getElementById('dummy') 
);       

Default props work great in the situation when the same default value can be utilized again and again for every instance of the component. Again reduce the LOC (line of code).  

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 functional 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”.     

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.     

It is not accessible to any component other than the one that owns it and sets it.     

You can learn about the state in this article.     

Can we use Props and State Together?   

Absolutely  ! Let’s understand with the following example how we can combine both state and props in our component.    

import React from 'react'; 
 
class App extends React.Component { 
   constructor(props) { 
       super(props); 
       this.state = { 
           heading: "Heading from props...", 
           content: "Some Content from props..."   //Line-8 
       } 
   } 
   render() {        //Line-11 
       return ( 
           <div> 
               <Header headingProp={this.state.heading} /> 
               <Content contentProp={this.state.content} /> 
           </div> 
       ); 
   } 
} 
class Header extends React.Component { 
   render() { 
       return ( 
           <div> 
               < h1 >{this.props.headingProp}</h1> 
           </div> 
       ); 
   } 
} 
class Content extends React.Component { 
   render() { 
       return ( 
           <div> 
               < h2 >{this.props.contentProp}</h2> 
           </div> 
       ); 
   } 
} 
export default App;          

An explanation for the above snippet:  

Here we have initialized and used the state in our parent component (line number 7-8) and we have used that state by passing it down the component tree using props.   

Inside the render() (line number 11), we are setting the props data as headerProp and contentProp used in child components which are <Header> component and <Content> component.   

Now, if you change the state in the parent component, all the child components get updated, because the single source pf data is State here!    

What are the differences between props and state?  

Let’s  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 Statei.e React uses the setState() method to update the object of a state (but within the component itself) 

Conclusion    

Props is a very crucial concept while learning React. 

In this article, you have learned about the lifeline of React, which is Props, and how we can use props in React. You have got clarity on why a component updates or re-renders when data in the props changes. 

We also saw that whenever data changes in props, the component will re-render. 

Last but not the least, let’s just recall the pointers of all of the above: 

  • Props are like parameters to a function  
  • Props cannot be changed, they are immutable  
  • A prop is a special keyword in React, that stands for properties  
  • Props can only be passed in a uni-direction i.e (parent to child)  
  • Props can be used to pass dynamic data to a component 
  • A component re-renders when data in the props change

Hope you find this article useful! Happy Learning     

Profile

KnowledgeHut

Author
KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.