Twitter LogoFacebook Logo
Props (Properties)
Learn what are component props and how to use them.
By: King

In React, props (short for "properties") are a way to pass data from a parent component to a child component. 


They are used to configure and customize components, allowing you to control their behavior and appearance.

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.


To do this, we used the concept or "props."

<MyFirstComponent title="Codeible.com"/>

In the above code snippet, we added a property (prop) call title for MyFirstComponent.


To access that value, inside the component's function, we just need to add a parameter - usually called props but it can be anything.

function MyFirstComponent ( props ) {

    return (
        <h1></h1>
    );
}

Then after we defined a parameter, we can access the title property by using the "dot" operator.

function MyFirstComponent ( props ) {

    return (
        <h1>{props.title}</h1>
    );
}

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


props.author

The children Prop

One important prop that is reserved by React is children.

This prop represents all the child elements inside the component's tags.

In HTML for example, we can add child elements to a div like this:

<div>

   <h1>Welcome to Codeible.com</h1>
   <p>You are learning React</p>
</div>

The same can be done with components.

<MyFirstComponent>

    <p>Text 1</p>
    <p>Text 2</p>
</MyFirstComponent>

However, doing this will not display the child elements. If you launch the React app with this component, nothing will show:

function MyFirstComponent(props){
    return (
        <div></div>
    );
}

export default MyFirstComponent;

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>

Image from Codeible.com

That's all for props!


Sign In