constposts=[{id:1,title:"Hello World",content:"Welcome to learning React!"},{id:2,title:"Installation",content:"You can install React via npm."},];functionBlog(){return(<div><div><h3>{posts[0].title}</h3><p>{posts[0].content}</p></div><div><h3>{posts[1].title}</h3><p>{posts[1].content}</p></div></div>);}
2) If there is 100 data
constposts=[{id:1,title:'Hello World',content:'Welcome to learning React!'},{id:2,title:'Installation',content:'You can install React via npm.'},{id:3,title:'reusable component',content:'render easy with reusable component.'},// ...{id:100,title:'I just got hired!',content:'OMG!'},];functionBlog(){return(<div><div><h3>{posts[0].title}</h3><p>{posts[0].content}</p></div><div><h3>{posts[1].title}</h3><p>{posts[1].content}</p></div>{// ...}<div><h3>{posts[99].title}</h3><p>{posts[99].content}</p></div>{// ... 98 * 4 more lines !!}</div>
);}
Use the array map method to make the part that needs to be written repeatedly into a function.
3) Using the array method [map]
functionBlog(){constpostToElement=(post)=>(<divkey={post.id}><h3>{post.title}</h3><p>{post.content}</p></div>);//Pass each post to a functionconstblogs=posts.map(postToElement);return<divclassName="post-wrapper">{blogs}</div>;}
You can use JSX to process the result of the map method inside the return statement by using any expression inside curly braces.(inline)
It is up to the developer to decide whether to extract it as a variable or put it inline for code readability.
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)