Learning React / Part 4: rendering content

Antonio P.R.
2 min readNov 24, 2021

--

Until now we have rendered JSX directly without including any loop or condition. Well, let’s see how we can improve our rendering to make it dynamically.

React render directly an array of components. It’s the way to iterate arrays and print each item in a reusable component.

You can use the javascript methods map and filter to modify or iterate your array.

An important thing is that React needs a unique identifier per element repeated in your DOM. For this use the attribute ‘key’.

With this key React recognize which component has changed, so improves the performance. In addition, if you have nested components with different states you ensure the states are handled correctly.

If you skip the use of the key attribute you’ll receive a warning in the console referencing the next link: https://reactjs.org/link/warning-keys

So, don’t forget to add unique keys to your elements.

const ExpensesComponent = (props) => {
// Iterate an array creating a new one formed by JSX
expensesContent = expenses.map(item => (
<ExpenseItem
key={item.id} //
expense={item}
/>
));
// Render the JSX array
return(<div>{expensesContent}</div>)
}

Now if we want to change the example above to render the array only if has content we can do it in an elegant way.

const ExpensesComponent = (props) => {
// Iterate an array creating a new one formed by JSX
expensesContent = expenses.map(item => (
<ExpenseItem
key={item.id} //
expense={item}
/>
));
if(expensesContent.length > 0){
// Render the JSX array
return(<div>{expensesContent}</div>)
}
return(<div>Content not found</div>)}

Of course, we can do the same with ternary or any other possible way. The example exposed is the most elegant way from my point of view.

Also, it’s important to know that you can pass a javascript object to the styles. It’s a good way to set conditional styles.

return(
// The style receives a javascript object
<div style={{height: 30px, backgroundColor: red}}>
{expensesContent}
</div>
)

— — —
Repo: https://github.com/antprt/learning-react

--

--