Render components in React

claireliao
1 min readOct 9, 2021

中文版連結

When we use React to develop the frontend, sometimes we need to render with the array and put the data in the view.

In our following example, we will use PRIMEREACT, React with redux&Typescript as the default setting, if you are not familiar with them, you can reading:

Start with React

Writing React with PRIMEREACT

0. Check Type of Array:

const arr:Array<string> = ['a','b','c','d','e'];

In this example, the target array arr is a string-type array. (You might use your self define type)

1. Provide the template for the array element

const drawCard = (element: string) => {
return (
<Card style={{width:'25rem',marginBottom:'2em'}}>
{element}
</Card>
);
}

Then we can draw every element in the array with this template.

2. Render the array in the component template.

return (
<div>
{arr.map((e)=>(drawCard(e)))}
</div>
);

note that the most important reason we use the map to render array is that map will return a new array, but forEach will not. (for reference: https://lcliao617.medium.com/javascript-array-46fda35f1062)

3. Full code:

import React from 'react';
import 'primeicons/primeicons.css';
import 'primereact/resources/themes/saga-blue/theme.css';
import 'primereact/resources/primereact.css';
import 'primeflex/primeflex.css';
import {Card} from 'primereact/card';
export function RenderArray(){
const arr:Array<string> = ['a','b','c','d','e'];
const drawCard = (element: string) => {
return (
<Card style={{width:'25rem',marginBottom:'2em'}}>
{element}
</Card>
);
}
return (
<div>
{arr.map((e)=>(drawCard(e)))}
</div>
);
}

Reference Project:

https://github.com/xiao617/primereact-example/tree/dev

--

--