Navigate back to the homepage
BLOG
Try NowLogin
Back

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

Felix Gerschau
December 14th, 2020 · 3 min read

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:

1const Card = () => {
2 return(
3 <div className="box">
4 <h1 className="title">react</h1>
5 <p className="category">verb</p>
6 <p>
7 1. act in response to something; respond in a particular way.
8 "he reacted angrily to the news of his dismissal"
9 </p>
10 </div>
11 );
12}

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.

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

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.

1<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:

1<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:

1<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.

1const Card = () => {
2 const card = {
3 title: 'react',
4 category: 'verb',
5 definition: `
6 1. act in response to something; respond in a particular way.
7 "he reacted angrily to the news of his dismissal"
8 `,
9 }
10
11 return(
12 <div className="box">
13 <h1 className="title">{card.title}</h1>
14 <p className="category">{card.category}</p>
15 <p>
16 {card.definition}
17 </p>
18 </div>
19 );
20}

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.

1const App = () => {
2 const card = {
3 title: 'react',
4 category: 'verb',
5 definition: `
6 1. act in response to something; respond in a particular way.
7 "he reacted angrily to the news of his dismissal"
8 `,
9 };
10
11 return (
12 <Card card={card} />
13 );
14}

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.

1const Card = (props) => {
2 const card = props.card;
3
4 return(
5 <div className="box">
6 <h1 className="title">{card.title}</h1>
7 <p className="category">{card.category}</p>
8 <p>
9 {card.definition}
10 </p>
11 </div>
12 );
13}

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

1class Card extends React.Component {
2 render() {
3 const card = this.props.card;
4 return(
5 <div className="box">
6 <h1 className="title">{card.title}</h1>
7 <p className="category">{card.category}</p>
8 <p>
9 {card.definition}
10 </p>
11 </div>
12 );
13 }
14}

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

1const App = () => {
2 const reactCard = {
3 title: 'react',
4 category: 'verb',
5 definition: `
6 1. act in response to something; respond in a particular way.
7 "he reacted angrily to the news of his dismissal"
8 `,
9 };
10
11 const nodeCard = {
12 title: 'node',
13 category: 'noun',
14 definition: `
15 1.
16 a point in a network or diagram at which lines or pathways intersect or branch.
17 `,
18 };
19
20 return (
21 <div>
22 <Card card={reactCard} />
23 <Card card={nodeCard} />
24 </div>
25 );
26}

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:

1const Wrapper = (props) => {
2 return (
3 <div>
4 <h1>Definitions</h1>
5 {props.children}
6 <h1>-</h1>
7 </div>
8 );
9}

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

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

1const App = () => {
2 const reactCard = {
3 title: 'react',
4 category: 'verb',
5 definition: `
6 1. act in response to something; respond in a particular way.
7 "he reacted angrily to the news of his dismissal"
8 `,
9 };
10
11 const nodeCard = {
12 title: 'node',
13 category: 'noun',
14 definition: `
15 1.
16 a point in a network or diagram at which lines or pathways intersect or branch.
17 `,
18 };
19
20 return (
21 <Wrapper>
22 <Card card={reactCard} />
23 <Card card={nodeCard} />
24 </Wrapper>
25 );
26}

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.

Observability for Production React Apps

Debugging React apps in production may be challenging and time consuming. Asayer is a frontend monitoring tool that replays everything your users do and shows how your app behaves and renders for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder.

Asayer Frontend Monitoring

Asayer helps to quickly get to the root cause by reproducing issues as if they happened in your own browser. It also monitors your frontend performance by capturing key metrics such as page load time, memory consumption and slow network requests as well as Redux actions/state.

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

More articles from Asayer Blog

Introducing Asayer Synthetics

Minimize downtime and be proactive by continuously monitoring your most critical user journeys in live environments with Asayer Synthetics.

November 13th, 2020 · 2 min read

How to Use Async Actions for Global State With React Hooks and Context

Optimize re-renders using state usage tracking with React Hooks, detect the usage in render, and triggers re-renders. For Redux/non-Redux.

November 4th, 2020 · 3 min read
© 2020 Asayer Blog
Link to $https://twitter.com/asayerioLink to $https://github.com/asayerioLink to $https://www.linkedin.com/company/18257552