Props is a short form form properties. Props in React.js allows you to pass in a variable(or property) from a parent to a child component. Therefore, it make a component dynamic.
1. Props in Functional Component
Assuming we have a child component, Greet.js. It displays a hello message to the user.
We will render the Greet component as child of the App component. However, we also want to pass the person’s name to it as well. The code below does that.
The parent component(App.js)
function App() { return ( <div className="App"> <Greet name="Kindson"> </Greet> </div> ); } export default App;
The child component(Hello.js)
import React from 'react' const Greet =(props) => { return ( <div> <h1>Hello {props.name}</h1> </div> ) } export default Greet
So what happens here is that when the App component loads the Greet component, it passes it a prop called name. Then the Greet component receives the prop as parameter and renders it as {prop.name}. The curly braces tells react the evaluate the content as JSX expression.
2. Using Children Props
When the parent component load the child component, it could add additional components. For instance, the in the code below, the parent component inserts a button and a textbox in between the <Greet> and </Greet> tags. This is the children props.
The child component can display this content using {props.children}.
App component
function App() { return ( <div className="App"> <Greet name="Kindson" heroName="The Tech Pro"> <button>This is Child prop</button> <br /> <input type="text" value="Another child prop"/> </Greet> </div> ); }
Child component
const Greet =(props) => { return ( <div> <h1>Hello {props.name}</h1> {props.children} </div> ) }
Note: I purposely omitted the import & export statements to keep the code simple.
3. Props in Class Component
For class component, the properties are passed the same way by the parent. However, in the child component, the properties are retrieved using the ‘this’ keyword. An example is given below
class Hello extends Component { render(){ return <h1>Welcome {this.props.name} </h1> } }
We should also note that props are immutable. This means the the child component alter the value of the prop. So, how then do assign values to a prop? That brings us the the next important topic: State.
[…] React.js – Props […]