Skip to main content

Command Palette

Search for a command to run...

React Props

Updated
2 min read
React Props

What are React Props?

We use props in React to pass data from one component to another (from a parent component to a child component). Props are just a shorter way of saying properties. They are useful when you want the flow of data in your app to be dynamic.

Use of React Props

Before we go deeper, it is important to note that React uses a one-way data flow. This means that data can only be transferred from the parent component to the child components. Also, all the data passed from the parent can't be changed by the child component.

This means that our data will be passed from App.js which is the parent component to Component.js which is the child component (and never the other way).

pass data parent component to child component with props?

Here is an example

class ParentComponent extends Component {    
    render() {    
        return (        
            <ChildComponent name="First Child" />    
        );  
    }
}

//ChildComponent
const ChildComponent = (props) => {    
    return <p>{props.name}</p>; 
};

Firstly, we need to define/get some data from the parent component and assign it to a child component’s “prop” attribute.

<ChildComponent name="First Child" />
  • “Name” is a defined prop here and contains text data. Then we can pass data with props like we’re giving an argument to a function:

    const ChildComponent = (props) => {  
    // statements
    };
    
  • And finally, we use dot notation to access the prop data and render it:

    return <p>{props.name}</p>;
    
  • Props in React js functional component:

    To access props in the Functional component, we don’t need to use the ‘this’ keyword, because in React Functional component accepts props as parameters and can be accessed directly.

    Example of props in React js functional component

    • Let’s say index.html contains the below statement inside the body tag:
```javascript
<div id="root"></div>
```

*   Next in the `index.js` file write the below code:


```javascript
import React from 'react';
import ReactDOM from 'react-dom/client';
function Welcome(props){
  return <h1>Hello, {props.name}</h1>
}


const root = ReactDOM.createRoot(document.getElementById('root'));
const elem= <Welcome name ="Sami"></Welcome>
root.render(elem);
```

So the above code renders `Hello, Sami` on the page:

This is how we can set `props` in React js functional component

More from this blog