React – Props

A typical React application can have tens to hundreds of different components. Props are what allows these various components to communicate and talk to each other properly; it is the way React passes data to components. They also look very similar to attributes in HTML.

Need For Props

According to the Official React Team, a component must be reusable across different applications. For a reusable component, it must be controllable, customizable, and can communicate with other components.

Say you have a component to display a text with a color you like, and you would like it to display in red color. Won’t the component need some way of communication to get the color information?

This is why props are essential. You will have to pass the color information as a prop to the component, just like an HTML attribute.

<Component color="red" />

This translates to the diagram below.

Structure of props

Props are written as a key-value pair similar to HTML attributes. To pass a prop to a component, specify the prop’s name and its value separated by an equal = sign.

For example, for a component named User, with the props: “fullname” and “address”, it would be written as below:

<User fullname={'John Doe'} address={'123 main Street, New York, NY'} />

Remember that a component name must be written first before specifying any props. Also, any two props must be separated by a space.

Prop Data Types

Props can be of different data types simply because JavaScript has types like Number, String, Boolean, Arrays, and Objects.
The list below shows the various ways that a prop can be passed.

1. Number

<Component prop={15} />

2. String

<Component prop={'string'} /> or <Component prop='string' />

3. Boolean

<Component prop={true} /> or <Component prop />
<Component prop={false} />

4. Array

<Component prop={['one', 'two', 'three']} />

5. Object

<Component prop={{ name: 'John', age: 30 }} />

6. Passing Multiple props

<Component prop='first' prop2={20} prop3={true} />

7. Passing a Variable

// You can pass any type of variable to a prop.
const myvar = 'test';
<Component prop={myvar} />

Prop Rules and Facts

  • Props are immutable. The component that receives the prop has no permission to change it.
  • You can pass one or many props to a component.
  • It is optional to pass a value to a prop. It takes a true Boolean value by default.

Therefore,

<Component hide /> is equivalent to
<Component hide={true} />

They are called attributes when you pass it to an HTML/JSX element but are known as props when you use it with Components!

Props with Functional Components

Every functional component receives an optional parameter that contains all the props passed to it. It is named as “props” and is purely a convention.

The key-value pairs that you pass to the component become the “props” object. You can access their values by using the dot notation.

Look at the Welcome component definition below. It takes the optional props parameter, which contains all the prop values passed to this component.

function Welcome(props) {
    return ( <div>
        <h1> Hello {
            props.username
        }! </h1> 
          <p>How are you?</p> 
             </div>
    )
}

On rendering the component, we need to pass the username as a prop.

<Welcome username=”John” />

It will then be accessible anywhere inside the component through props.username as seen in the example code above. The output will look like this:

Hello John
How are you?

You can reuse the same component multiple times with different prop values. This is how a component becomes more reusable through props.

Props in Class Components

Class components follow a similar way in rendering the props and displaying the data. The only difference is that you access props using the this keyword in JavaScript in-class components.

Accessing props inside a class component

We can access the passed props anywhere inside a class component by using this.propsName

If we have a component say:

<Loading text=’loading…’ />

We can use this.props.text to access it inside the render method like so:

class Loading extends React.Component {
    render() {
        return ( <div> {
                this.props.text
            }    </div>
        )
    }
}

Just remember to replace “props” with this.props inside a class component. The rest of the rules are the same.

Props Inside the Class Constructor

A constructor is a lifecycle function that runs once at the beginning when a component is created. Sometimes you will need props inside a class constructor to initialize the state.

Similar to a functional component, the constructor method takes a “props” argument. So, inside the constructor, you can access “props” without using the this keyword.

class MyComponent extends React.Component {
    constructor(props) {
        console.log(props);
    }
}

However, if you want to use this.props or even the this keyword inside the constructor, you must invoke the super(props) or super() method.

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log(this, this.props, props);
    }
}

Children Props

Children’s props give you access to the nested components. Just like nesting tags in HTML, you can nest JSX elements and components.

These nested elements are passed to the component automatically by react as the “children” prop.

If you render a component as below:

<MyComponent >
    <h1> Hello < /h1> 
    <SomeComponent />
    <p> Text </p> 
</MyComponent>

Then you can access the react elements inside the component by using the special props.children property. It is very useful to dynamically render the child elements inside a component.

function MyComponent(props) {
    return ( <div>
        <h1> Children </h1> {
            props.children
        } {
            /*
            props.children will render/convert dynamically into:
            <h1>Hello</h1>
            <SomeComponent/>
            <p>Text</p>
            */
        }   </div>
    )
}

For class components, we will have to use this.props.children instead of props.children to access the child elements.

Common Use of props

1. Rendering Data

The most common use of props is to render data. You can pass a text or a list of items, and then the component displays the passed prop.

2. Changing a component’s behavior

A component also needs a prop to determine its functionality. For example, you can pass a prop to toggle show/hide a dialog box. In this case, it does not use the data to render/display it.

Summary

Using props, we can send data and information to a component. Props are important to make a component reusable and controllable. It also makes a component more flexible and useful.

Without props, components are static and lifeless. What we see as interactive web development in React wouldn’t have been possible without props.

Now, go ahead and try experimenting with the knowledge that you gained about “props” with different components.

Back to: React Tutorial > Learn React

Leave a Reply

Your email address will not be published. Required fields are marked *