Home > Net >  Render an array of components in React/TypeScript?
Render an array of components in React/TypeScript?

Time:06-15

I'm currently trying to render an array of JSX Components. I see two possible ways for me to do this.

One(current approach): Make the array of type object that holds the properties of the component and then construct the JSX component in line using the array contents as props

const todos = { title:string,content:string }[];
todos.map((todo:{ title:string,content:string })=>{<TitleCard title={todo.title}/>;

Two: Make the array of type JSX elements so the array stores the pure JSX Element and just plops it down with a .map inside a render function. I find the first approach to be more clean, but it requires a bit more work in terms of constructing the JSX elements from the props in the array.

Which approach would be the correct/best way to go about this? Appreciate the help.

CodePudding user response:

I'm not sure if I understand your second approach but first one sounds good. I cleaned the code up a bit and this is the way to go:

 type Todo = {
   title:string,
   content: string
 }
    
 // this data(todos) probably will come from your props but I added some 
 // dummy data for demonstration purpose
 const todos: Todo[] = [
  {title:"title1", content:"content1"}, 
  {title:"title2",content:"content2"}
 ];
    
 const mappedTodosToRender = todos.map(({title})=>{<TitleCard key={title} title={title}/>;

 return (
  <>
    {mappedTodosToRender}
  </>
 )

  • Related