Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array to component property in React

How can I pass an array to a component as a property. Neither of the following achieve what I am looking for. I want to pass the array of items through, manipulate them in the component and output in the render method.

<List columns=['one', 'two', 'three', 'four'] /> // unexpected token
<List columns="['one', 'two', 'three', 'four']" /> // passed through as string not array

Is there a standard syntax or best practice for this kind of thing?

like image 353
Guy Avatar asked Jan 15 '16 01:01

Guy


People also ask

Can React props be an array?

As you all know, properties which are shortly called as props is one of fundamental blocks of React. Props will allow you to pass the parameters between the components, they could be strings, numbers, object or arrays. Here is the simple example of using the props.

Can you have an array of React components?

To render an array of components in React you simply need to pass the array into JSX by wrapping it in curly braces, just be sure that your components each have a unique key prop because React will use this when rendering it to avoid bugs.

How do you pass an object as a prop in React?

Use the spread syntax (...) to pass an object as props to a React component, e.g. <Person {... obj} /> . The spread syntax will unpack all of the properties of the object and pass them as props to the specified component. Copied!


1 Answers

You need to use {} around js expressions:

<List columns={['one', 'two', 'three', 'four']} />
like image 54
rojoca Avatar answered Oct 08 '22 00:10

rojoca