Lists and Arrays in React

Trey Alexander Davis
Byte-sized React
Published in
3 min readSep 9, 2017

Often you’ll have a data collection that you want to iterate over and render React components for each item in the array.

We can do this by creating an array of React elements. We can simply do this by utilizing the map function on adata array. By returning JSX in our map function, Babel will convert the JSX to React elements.

const reactElementsArray = dataArray.map((data) => {
return (
<p>{data}</p>
);
});

We then include the React element array as an expression in JSX to render the array:

const reactComponent = props => {
return(
<div>{reactElementsArray}</div>
);
};

Take a look at this process visually:

Now let’s walk through and example in CodePen- if you don’t know how to set up CodePen for React, you can check out this story.

We are going to make a list of famous quotes- let’s start by adding our quote data to the JS file:

const quotes = [
{text: 'Whatever the mind of man can conceive and believe, it can achieve.',
author: 'Napoleon Hill'},
{text: 'Strive not to be a success, but rather to be of value.',
author: 'Albert Einstein'},
{text: 'I attribute my success to this: I never gave or took any excuse.',
author: 'Florence Nightingale'},
{text: 'You miss 100% of the shots you don’t take.',
author: 'Wayne Gretzky'}
];

Now let’s add our quote component which will render the quote text and the quote author:

const Quote = props => {
return (
<div>
<h4>{props.text}</h4>
<p>{props.author}</p>
</div>
);
};
Quote.propTypes = {
text: React.PropTypes.string,
author: React.PropTypes.string
}

Notice how we will be accessing the quote and its author via the component’s props.

Next let’s add our app component that will render our quotes:

const App = props => {
const quoteArray = props.quotes.map((quote) => {
return (
<Quote text={quote.text} author={quote.author} />
);
});
return (
<div>
<h2>Famous Quotes</h2>
{quoteArray}
</div>
);
};
App.propTypes = {
quotes: React.PropTypes.array
}

Notice how we used the map function to generate our React element array and then used the curly braces to insert the quoteArray as a JavaScript expression in the App component. This will return all of the Quote components in our quoteArray.

Now render the App component:

ReactDOM.render(
<App quotes={quotes} />,
document.getElementById('root')
);

Now your CodePen should look like this (be sure to include the root div in the HTML file):

Here is the CodePen:

So far our React components have been looking rather plain- next we’ll take a look at applying some simple styling to jazz things up.

--

--