2

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.

1 Answer 1

3

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}
  </>
 )

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! If I plan on the titles being non-unique, should I use key={index} instead?
You could also use uuid package: github.com/uuidjs/uuid. It is not recommended to use indexes which are coming from map. You can find more info here in React official doc: reactjs.org/docs/….
Awesome, I will look into UUID and the recs for key values. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.