Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Pass Properties Object to Child Component

Jan 9, 2020 • 11 Minute Read

Introduction

React is a JavaScript-based library used to create an excellent user interface, and by using it, we can create different UI components.

It is one of the most popular JavaScript-based libraries due to its utterly robust foundation and vital community support sources around the globe.

In this guide, we'll learn about props in React, including how to declare them and how to pass a properties object to a child component.

What are Props in React?

React is a component-based library where each application can be divided into components that act as single, generic units in order to serve any specific functionality.

There are several concepts that form the backbone of React, but one of the most talked-about topics is props. Props in React are pieces of information, or in other words, we can say that props are read-only data that can be passed and used by the various components into the application.

Props are generally a static value, objects, or maybe an array. By using these pieces of data, we can communicate each of the components by passing them to the child or moving them to the parent from the child component.

How to Declare Props?

Props is short for properties and denotes the information to be used by something. In React, props can be declared by giving the appropriate name along with the suitable value that we need to pass.

To declare a props, we should provide the unique name along with the components or element, as shown below using the file index.js.

      import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";
import DemoComponent from "./DemoComponent";

class App extends Component {
  constructor() {
    super();
    this.state = {
    };
  }

  render() {
    return (
      <div>
        <DemoComponent
          name={"Test"}
          age={25}
          email={"[email protected]"}
          salary={66.5}
        />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

Here in this example, we have one child component in which we are going to pass the different properties so that the DemoComponent can consume it, and the source code is shown below.

Nname, age, email, and salary are the independent props names, and along with the props, we have provided the suitable values. After giving the props to the child component, we need to access them.

To access the props passed from the parent component, we can easily consume them into the child component, like this.

DemoComponent.js

      import React, { Component } from "react";

class DemoComponent extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    const { name, age, email, salary } = this.props;
    return (
      <div>
        <table>
          <tr>
            <td>Name is : {name}</td>
          </tr>
          <tr>
            <td>Age is : {age}</td>
          </tr>
          <tr>
            <td>Email is : {email}</td>
          </tr>
          <tr>
            <td>Salary is : {salary}</td>
          </tr>
        </table>
      </div>
    );
  }
}

export default DemoComponent;
    

You can see the DemoComponent file, which is our child component, but one thing to note is how we accessed the props.

      const { name, age, email, salary } = this.props;
    

This way, every prop will be stored as a const, and we can access it whenever we want. But keep in mind that we won’t be able to change it because all props are read-only.

We can also access the props directly, like this.

      render() {
    return (
      <div>
        <table>
          <tr>
            <td>Name is : {this.props.name}</td>
          </tr>
          <tr>
            <td>Age is : {this.props.age}</td>
          </tr>
          <tr>
            <td>Email is : {this.props.email}</td>
          </tr>
          <tr>
            <td>Salary is : {this.props.salary}</td>
          </tr>
        </table>
      </div>
    );
  }
}
    

This is how we can use the props directly, using this.props followed by the specific props name, which is forwarded by the parent component to the child component.

How to Pass an Object as Props to the Child Component

We have just seen how to pass separate values as props and consume it into the child component, but this has its limits; thus, we may sometimes need to pass array or object as a prop.

The object is one of the most widely used terms in JavaScript. It is used pass the group of keys and value pairs and consume it by using the different key names.

We can also pass the complete object to the child component as a prop and can consume it just like we do with the standard static props.

Open the index.js file and replace the following lines of source code.

      import React, { Component } from "react";
import { render } from "react-dom";
import "./style.css";
import ChildComponent1 from "./ChildComponent1";

class App extends Component {
  constructor() {
    super();
    this.state = {
      employee: {
        empCode: "119",
        name: "Test employee",
        age: "25",
        email: "[email protected]",
        location: "Hyderabad"
      }
    };
  }

  render() {
    return (
      <div>
        /* Used employee as props name */
        <ChildComponent1 employee={this.state.employee} />
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

In this example, we have created a straightforward object into the state. It is called employee and looks like this.

      employee: {
        empCode: "119",
        name: "Test employee",
        age: "25",
        email: "[email protected]",
        location: "Hyderabad."
}
    

The object contains the basic properties of a single employee, including code, name, age, and other information being used in the child component.

Now let’s consume the complete employee props into the child component, create a new file called ChildComponent1.js, and paste the following lines of source code.

      import React, { Component } from "react";

class ChildComponent1 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    // Used employee props
    const { employee } = this.props;
    return (
      <div>
        <table>
          <tr>
            <td>Employee Code : {employee.empCode}</td>
          </tr>
          <tr>
            <td>Employee Name : {employee.name}</td>
          </tr>
          <tr>
            <td>Employee Age : {employee.age}</td>
          </tr>
          <tr>
            <td>Employee Email : {employee.email}</td>
          </tr>
          <tr>
            <td>Employee Location : {employee.location}</td>
          </tr>
        </table>
      </div>
    );
  }
}

export default ChildComponent1;
    

Here in this example, we have consumed the employee props, but the way we access the props as object is pretty different compared to the normal props.

      <tr>
    <td>Employee Code : {employee.empCode}</td>
</tr>
    

The employee props are an object that contains the number of different keys along with the value, so if we want to access any specific key, then we need to write an object name along with the key so that it can be used to render the values.

In the same way, we can also pass the array as a prop, but the way to access the props will be different.

This is how we have passed and consumed the props as an object from the parent component to the child component, but we can also pass the complete element as props to the child component, which we will learn next.

How to Pass an Element as a Prop?

So far in this guide we have looked at different examples of how to pass the standard props, objects as props, but apart from these options, we can also pass HTML elements as props in React.

The element we want to pass will be rendered into the child and can be moved from the parent as a complete element between the tags of the child component.

Let’s directly jump into the example, which shows the div element passed to the child component as props.

Open the file called index.js and paste the following lines of source code.

      import React, { Component } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import ChildComponent2 from "./ChildComponent2";

class App extends Component {
  constructor() {
    super();
    this.state = {
      message: ""
    };
  }

  render() {
    return (
      <div>
        <ChildComponent2>
          <div>This is div 1</div>
          <div>This is div 2</div>
          <div>This is div 3</div>
        </ChildComponent2>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));
    

The child component name is ChildComponent2, but if you notice, we haven't used any props name that we usually use with the other approach.

Here in this example, we have used three different div elements surrounded by the child component name. This means all these elements will be a prop for the child component.

Now let’s consume it into the child component, ChildComponent2.js, like this.

      import React, { Component } from "react";

class ChildComponent2 extends Component {
  constructor() {
    super();
    this.state = {
      name: "React"
    };
  }

  render() {
    const { children } = this.props;
    return <div>{this.props.children}</div>;
  }
}

export default ChildComponent2;
    

As you can see, we just have used the props name children. Thismeans it’s a default property if any element is passed as props from the parent component.

In other words, we can say the children property is what we have included in between the opening and closing tag of the component.

A single statement to understand:

      <div>{this.props.children}</div>
    

The props.children is a way to access the child elements that are being passed between the opening and closing child component tag, like this.

      <ChildComponent2>
    <div>This is div 1</div>
    <div>This is div 2</div>
    <div>This is div 3</div>
</ChildComponent2>
    

This means that when we send the data as an HTML element, it will be identified by the children property and at last the children will be rendered based on the specification.

This is how we can pass the different HTML elements as props and can consume it using the props. Children property renders the data coming from the parent component.

Conclusion

In this guide, we have learned the backbone of any React app, which is props. We have also discussed creating and consuming the props from the parent component to the child component.

We then learned a critical way of passing props as an object, which is the widely used method of passing props and consuming it into the child component. I hope this guide helps you to understand props. Stay tuned for more new guides on React.js.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author