A Great Example to Understand the Usage of ReactJS Props

How to Use Props in ReactJS

Components are reusable, so you can create a component that returns any JSX you want to and includes it in any part of your app. So, in this article, we will see how to use props in Reactjs

Example:

We have a functional component called greet() and that function has “Hello John”. If we want to duplicate it twice, we need to put the Greet tag twice in the parent component.

Greet component:

import React from 'react';
const Greet = () => <h1> Hello john </h1>

export default Greet

App component:

import React from 'react';
import Greet from './Greet'
import ReactDom from 'react-dom';

const App = () =>{
return(
<div>
<Greet/>
<Greet/>
</div>
) }

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

Output:

how to use props in reactjs

But this way doesn’t really help what would be great is if we could pass in the name of the person we wanted to create a greet. That way reusing the same component, we could greet three different people instead of greeting “hello john” three times. That is where props come into the picture. Props are a short form of properties and it is the optional input that your component can accept it. It also allows the component to be dynamic. So, let’s see how to use props in ReactJS

Using Props

So, here are intention is to pass a name from the app component to the greet component and render that name in the browser. To specify props for a component, we specify them as attributes. To specify a ‘name’ property we simply add the name attribute in the App return and then we assign the value like the below code.

const App = () =>{
return(
<div>
 <Greet name="Bruce"/>
 <Greet name="Clark"/>
 <Greet name="Diana"/>
</div>
 ) 
 }

Now we are sending some information or some property to the Greet component. To retrieve these values in the Greet component, we do two steps.

READ ALSO  Easy Steps to Using React useState Hooks with Object

Step 1:
Add the “props” parameter to the Greet functional component, like the below code.

const Greet = (props) => {
return(
<h1> Hello john </h1>
)
}

Step 2:
To use the display name attribute value to the Greet function, we need to put “{props.name}” in the Greet function body like the below code. If you pass another attribute in the App component instead of “name”, then we need to change and put that attribute name in the Greet component.

const Greet = (props) => {
return(
 <h1> Hello {props.name} </h1>
  )
}

So, our props full code is:

Greet component (Greet.js):

const Greet = (props) => {
return(
<h1> Hello {props.name} </h1>
)
}

App component (App.js):

const App = () =>{
return(
<div>
<Greet name="Bruce"/>
<Greet name="Clark"/>
<Greet name="Diana"/>
</div>
) }

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

Output:

how to use props in reactjs

See, the above output we can change the value of component using props

Leave a Reply