Back

How to Use Props to Pass Data to Child Components in React.js

How to Use Props to Pass Data to Child Components in React.js

Typically, React applications are composed of many smaller components. In React, this can be everything, starting with a button, up to an entire form or page. Given the following word definition card, for instance, we might want to break it down into smaller components.

text

The React component of that card looks like this:

const Card = () => {
  return(
    <div className="box">
      <h1 className="title">react</h1>
      <p className="category">verb</p>
      <p>
        1. act in response to something; respond in a particular way.
        "he reacted angrily to the news of his dismissal"
      </p>
    </div>
  );
}

You can check out the entire code on this codepen.

This structure is fine if you only want to show one card, but what happens when you want to make this component reusable?

This is where React’s props come into play.

What are “props” in React?

Props is a common keyword in React, which is short for property.

They are to React components what arguments are to functions.

function sum(a, b) {
  return a + b;
}

The variables a and b are the arguments of that function.

The syntax of props in JSX (the syntax extension to JavaScript that is commonly used in React), is just very similar to the syntax of HTML properties, accepting key-value pairs inside the tag.

<script src="/index.js"></script>

In this example, src is a property with the value /index.js.

In React, we can define props with a similar syntax:

<Component key={value} />

Note the curly braces around value. Everything inside those braces will be interpreted as JavaScript, which allows us to pass down variables and objects as well.

If your value happens to be a string, you can also use the HTML syntax like this:

<Component key="value" />

Just like in functions you can’t pass arguments to the caller, you can only pass props from a parent to a child component.

It’s important to note that props are read-only, which means they shouldn’t be modified by the child component.

How to use React props

Passing props from the parent to the child component

Let’s have a look at the example from above again. We have a Card component, which renders the definition of the word react. We now want to make this component reusable.

We start by replacing the hardcoded values of the component with variables.

const Card = () => {
  const card = {
    title: 'react',
    category: 'verb',
    definition: `
        1. act in response to something; respond in a particular way.
        "he reacted angrily to the news of his dismissal"
    `,
  }

  return(
    <div className="box">
      <h1 className="title">{card.title}</h1>
      <p className="category">{card.category}</p>
      <p>
        {card.definition}
      </p>
    </div>
  );
}

I decided to store the values in one object instead of multiple variables. You can do it either way.

The next step is to move the variables to the parent component and pass it down as a prop.

const App = () => {
  const card = {
    title: 'react',
    category: 'verb',
    definition: `
        1. act in response to something; respond in a particular way.
        "he reacted angrily to the news of his dismissal"
    `,
  };

  return (
    <Card card={card} />
  );
}

Note how we wrap the variable in curly brackets.

Accessing props in the child component

The last step is to access the props in the child component.

In function components, we access the props through the first function argument. Since we called our new prop card, we can access it through props.card.

const Card = (props) => {
  const card = props.card;
  
  return(
    <div className="box">
      <h1 className="title">{card.title}</h1>
      <p className="category">{card.category}</p>
      <p>
        {card.definition}
      </p>
    </div>
  );
}

If we were using class components, we could access it through this.props.card.

class Card extends React.Component {
  render() {
    const card = this.props.card;
    return(
      <div className="box">
        <h1 className="title">{card.title}</h1>
        <p className="category">{card.category}</p>
        <p>
          {card.definition}
        </p>
      </div>
    );
  }
}

With this new structure in place, we can easily add more cards without rewriting any code.

const App = () => {
  const reactCard = {
    title: 'react',
    category: 'verb',
    definition: `
        1. act in response to something; respond in a particular way.
        "he reacted angrily to the news of his dismissal"
    `,
  };

  const nodeCard = {
    title: 'node',
    category: 'noun',
    definition: `
        1.
        a point in a network or diagram at which lines or pathways intersect or branch.
    `,
  };

  return (
    <div>
      <Card card={reactCard} />
      <Card card={nodeCard} />
    </div>
  );
}

This is how it looks like:

text

Why should we use props?

If you start a React application, you need to use props at some point or another, unless you only want to use one component (which in theory is possible).

Structuring your application in a way that allows you to reuse components will make maintaining the application and adding new features much easier.

In real-life applications that are under constant development, components inevitably grow over time. However, when you get to a point where you need to reuse parts of that component, you can refactor the code and create more reusable components out of one, just like we did in the example above.

Keeping the codebase readable and loosely coupled is an ongoing effort, but React simplifies this for us with its component-based approached.

A special case: The “children” prop

Before we wrap this up, there’s one more thing I want you to know about: The children prop.

This is a special one since it’s always available without explicitly passing it down. It allows us to write components that wrap around others.

In the example above, we might want to add a wrapper component with a headline:

const Wrapper = (props) => {
  return (
    <div>
      <h1>Definitions</h1>
      {props.children}
      <h1>-</h1>
    </div>
  );
}

We can simply put props.children where we want the children to appear.

In our App component, we then use this wrapper like that:

const App = () => {
  const reactCard = {
    title: 'react',
    category: 'verb',
    definition: `
        1. act in response to something; respond in a particular way.
        "he reacted angrily to the news of his dismissal"
    `,
  };
  
  const nodeCard = {
    title: 'node',
    category: 'noun',
    definition: `
        1.
        a point in a network or diagram at which lines or pathways intersect or branch.
    `,
  };
  
  return (
    <Wrapper>
      <Card card={reactCard} />
      <Card card={nodeCard} />
    </Wrapper>
  );
}

text

Conclusion

I hope that this article made you understand this concept a little better. Feel free to play around with the codepen I created by adding more properties to the Card element.

React’s way of handling data can be quite different from other frameworks, but once you get used to it, the component-based architecture can become a very powerful tool.

Open Source Session Replay

OpenReplay is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data.

replayer.png

Start enjoying your debugging experience - start using OpenReplay for free.