DEV Community

Yahaya Kehinde
Yahaya Kehinde

Posted on • Updated on

Props in React

A very important part of React is the use of “props” which is a special keyword that stands for “properties” and refers to a way of passing data from one component to another. It is vital to note that data within props are passed in a uni-directional flow(meaning data can only be passed in one direction, usually from the parent component to the child/children components.

In order to understand props, we must first take into consideration the concept of “component rendering “

What is Component Rendering?

Let’s explain using code :

Alt Text

In the code sample above, we have two function based components, “App” and “Element”. Notice how the App component is passed into the Element component within the “return” method. This <App/> syntax means the App component is rendered within the Element component in order to be displayed on the web page.

How do we use props?

In order to use props, we pass a property which we can name anything we like as an attribute to the rendered child component within the return method of the parent component. Thereafter we pass props as a parameter within the child component and props.attribute-name into the JSX of the child component enclosed in curly brackets whenever we want to reference the props. Remember that anytime we want to reference any JavaScript syntax within JSX , we must enclose it in curly brackets.

Take a Look at the syntax below for passing props into function based components :

Alt Text

Please note that when we want to pass props into a class based component, the syntax changes slightly by the addition of this in front of the props such as this.props.attribute-name

Alt Text

USING PROPS.CHILDREN

Suppose we have a new function component named “Word” which we want to render within the “Element “ component by nesting it within the App component. Notice how we split the rendered <App/> into <App></App> so that we can nest the Word component within it. We then pass in this.props.children to the App component.

Look at the syntax below:

Alt Text

In conclusion

Props are a very important part of React and they ensure that data can be passed from one component to another. This simple concept makes it easy for components to be reusable and to be able to interact with one another.

Top comments (0)