Files
freeCodeCamp/guide/english/certifications/front-end-libraries/react/pass-an-array-as-props/index.md

55 lines
1.1 KiB
Markdown
Raw Normal View History

2018-10-12 15:37:13 -04:00
---
title: Pass an Array as Props
---
# Pass an Array as Props
2018-10-12 15:37:13 -04:00
---
## Problem Explanation
2018-10-12 15:37:13 -04:00
To pass an array as a prop, first an array must be declared as a "tasks" prop on each of the components to be rendered:
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
2018-10-12 15:37:13 -04:00
```javascript
const List = props => {
return <p></p>;
2018-10-12 15:37:13 -04:00
};
class ToDo extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h1>To Do Lists</h1>
<h2>Today</h2>
<List tasks={["Walk", "Cook", "Bake"]} />
<h2>Tomorrow</h2>
<List tasks={["Study", "Code", "Eat"]} />
2018-10-12 15:37:13 -04:00
</div>
);
}
}
2018-10-12 15:37:13 -04:00
```
Then, the props must be handled inside the "List" component:
```javascript
const List = props => {
return <p>{props.tasks.join(", ")}</p>;
2018-10-12 15:37:13 -04:00
};
// ... same as above
```
#### Code Explanation
2018-10-12 15:37:13 -04:00
* The `.join(", ")` method is used to take each element from within the array and join them into a string to be displayed.
* We are using the modularity of React in this example to display the tasks passed by two different components to a common component which renders the final HTML.
</details>
2018-10-12 15:37:13 -04:00