In React, props (short for "properties") are a way to pass data from a parent component to a child component.
In React, props (short for "properties") are a way to pass data from a parent component to a child component.
How it works
So far, the component(s) we created are using variables and properties that are within the component. However, since React applications are component based applications, there can have many components in a single page and sometimes you may want to pass data between components.
<MyFirstComponent title="Codeible.com"/>
In the above code snippet, we added a property (prop) call title for MyFirstComponent.
function MyFirstComponent ( props ) {
Then after we defined a parameter, we can access the title property by using the "dot" operator.
function MyFirstComponent ( props ) {
Note that we can add as many props as we need and not just one. See the same example with 3 properties.
<MyFirstComponent title="Codeible.com" course="React" author="King"/>
Then to access the values, we do the same for the title.
props.course
The children Prop
One important prop that is reserved by React is children.
<div>
The same can be done with components.
<MyFirstComponent>
However, doing this will not display the child elements. If you launch the React app with this component, nothing will show:
To display the child elements (the ones inside the component tags), we need to get the children property from the props variable.
props.children
With that, we can use interpolation and put the child elements inside the div element.
<div>{ props.children }</div>
That's all for props!