Pass An Array As Prop To A Component In React.js

Pass an Array as prop to a component in React.js

This article will show you how to pass an array as prop to a component in React.js. Here are some ways to do it with examples to make it easier for readers to understand.

Pass an array as prop to a component in React.js

Passing props as a variable containing the array

The prop is an acronym for Properties. You can imagine that Props is quite similar to the Attributes of HTML tags.

In the example below, we can pass an array as props from App to the component List. Let’s see the code to understand more about how to do it.

Code:

import React from "react";

const List = (props) => {
  return <p>{props.list.join(", ")}</p>;
};
 
class App extends React.Component {
  constructor(props) {
    super(props);
  }
 
  render() {
    const vehicles = ["Car", "Bike"];
    const animals = ["Dog", "Cat", "Bear"];
    return (
      <div>
        <h2>Pass an Array as prop to a component | LearnShareIT </h2>
        <hr/>
        <h3>Vehicle:</h3>
        <List list={vehicles} />
        <h3>Animal:</h3>
        <List list={animals} />
      </div>
    );
  }
}

Output:

As you can see, the array vehicle and array animal passed the props list to the List component and then rendered to the <p> tag. Or you can follow up on how to do it in the next part of the article.

Passing props array inline

Inline Element is a general term for HTML tags that, when declared in content, will still be in line with other documents. As mentioned above, props are like attributes in HTML, so writing and passing props inline is possible.

In this way, we do the same thing as above, but the array will be passed as an inline written directly to the child component’s props.

Code:

function Rapper({rappers}) {
  return (
    <div>
      {rappers.map(name => {
        return <p key={name}>{name}</p>;
      })}
    </div>
  )
}
 
function ParentComponent() {
  return (
    <div>
      <h2>Pass an Array as prop to a component | LearnShareIT</h2>
      <h3>Best Rapper :</h3>
      <Rapper rappers={['Eminem', '50 cent', 'Dr Dre', 'Snoop Dogg']} />
    </div>
  );
}

Output:

You can easily see the difference. The array here is placed directly in {} pairs and does not have to be defined as a private variable. Still, it will be more challenging to modify the array on the developer side. Hope these methods will be helpful to you.

Summary

To summarize, this article has shown you some ways to pass an array as prop to a component in React.js. You can do it by passing props as a variable containing array method or passing props array inline. Let’s try these methods. They are helpful for you.

Maybe you are interested:

Leave a Reply

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