How to Create and Pass Props to Child Components in React

There is one problem with our Card component from the previous lesson. The information in the card is hardcoded, which means all the articles will have the same image, same title, same description, and the same link.

That is not realistic at all. We need the cards to have the same layout and appearance, but they should contain different information.

However, as we just discussed, variables defined inside a component is private to that component. Other component don't have access to them. But in this case, we must pass data from a parent to a child component.

This is where props come in. It is a portal for us to pass data between components. For example,

jsx
1export default function App() {
2  const title = "Introduction to Next.js";
3  const description =
4    "Learn how to build scalable and performant websites using Next.js.";
5  const imageUrl = "https://via.placeholder.com/400x200";
6  const link = "/";
7
8  return (
9    <Card
10      imageUrl={imageUrl}
11      title={title}
12      description={description}
13      link={link}
14    />
15  );
16}

As you can see, the props can be passed to child components as if you are assigning attributes, except that the value needs to be wrapped inside a pair of curly braces ({}). This is to make sure whatever is inside will be interpreted as JavaScript, allowing you to pass different types of data.

For instance, you can pass strings, numbers, Boolean values, or even something more complex such as arrays and objects.

jsx
1export default function App() {
2  const title = "Introduction to Next.js";
3  const description =
4    "Learn how to build scalable and performant websites using Next.js.";
5  const imageUrl = "https://via.placeholder.com/400x200";
6  const link = "/";
7
8  return (
9    <Card
10      imageUrl={imageUrl}
11      title={title}
12      description={description}
13      link={link}
14    />
15  );
16}

The props will be passed to Card as an object. In fact, it is the only input argument your React component will receive. You can then read these props inside Card like this:

jsx
1export default function Card({ imageUrl, title, description, link }) {
2  return (
3    <div className="bg-white shadow-md rounded-lg overflow-hidden">
4      <img src={imageUrl} alt={title} className="w-full h-48 object-cover" />
5      <div className="p-6">
6        <h2 className="text-2xl font-bold mb-2">{title}</h2>
7        <p className="text-gray-700 mb-4">{description}</p>
8        <a href={link} className="text-blue-500 hover:text-blue-700">
9          Read more
10        </a>
11      </div>
12    </div>
13  );
14}

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉