How To Use Props In React

Introduction 

In this article, we will cover Props in React and how to use it in our application. So, let’s start.

What is Props?

Props stand for "Properties." They are read-only components. It is an object which stores the value of attributes of a tag and works similar to the HTML attributes.

We use Props in React to pass data from one component to another (from a parent component to a child component(s)).

Props are immutable so we cannot modify the props from inside the component. Inside the components, we can add attributes called props.

How to use props?

Let’s create a simple component in our react js app and named it “PropsDemo.js” as below.

How to Use Props in React

Let’s use this component in app.js file and try to run the application using “npm start” as expected it will simply print a message given in PropsDemo.js file.

How to Use Props in React

Now, suppose “PropsDemo” component is reusable in our app and we want to pass various fruit type in every component in such a way that fruit name in message should be dynamic.

e.g. Apple is my favorite fruit!! Or Mango is my favorite fruit!! Etc.

Let’s try it.

Since PropsDemo component is reusable, we can use it multiple times.

How to Use Props in React

To use props, you have to pass in props as an argument in your function. This is similar to passing arguments into your regular JavaScript functions.

Pass an attribute in the component and name it as fruit (this can be any name whatever you like to give) and different types of fruit in each component as below.

Code

import logo from './logo.svg';
import './App.css';
import PropsDemo from './PropsDemo';
function App() {
return (
    <div className="App">
        <h1>Welcome to rect js application</h1>
        <PropsDemo fruit = "Mango"/>
        <PropsDemo fruit = "Apple"/>
        <PropsDemo fruit = "Banana"/>
    </div>
   );
}
export default App;

How to Use Props in React

Now, PropsDemo component will have an argument named as “props” which will have all attributes from parent component.

  • Use props in component
  • Fetch attribute sent from parent component using props.fruit
  • Use jsx to print the value using { }

Code

function PropsDemo(props){
var fruitName = props.fruit;
    return(
        <div>
            <h3>{fruitName} is my favorite fruit!!</h3>
        </div>
       )
   }
export default PropsDemo;

How to Use Props in React

Let’s try to run the app and see output. We have passed three different fruit from three components and all are getting printed as expected.

How to Use Props in React

Summary

This article covered everything you need to get started using props and passing data dynamically across your components.

The best way to understand these concepts is to practice and build awesome stuff with them, so make sure you don't just read through – go build, too.