简体   繁体   中英

Return HTML tag in array of object map

I have an array of objects mapping to return as a component but some of the content has an HTML tag. How can I return it rendering the HTML tag inside it?

const listContent = [
  {
    title: 'Sample Title 1',
    content: 'Sample of only text here'
  },
  {
    title: 'Sample Title 2',
    content: 'Sample of only text here with <span>Should render as span</span>'
  },
];


{listItemContent.map(item => (
  <ListItem>
    <h1>{item.title}</h1>
    <p>{item.content}</p>
  </ListItem>
))}

You probably want to use React fragments , like so:

const listContent = [
  {
    title: 'Sample Title 1',
    content: 'Sample of only text here'
  },
  {
    title: 'Sample Title 2',
    content: <>
      Sample of only text here with <span>Should render as span</span>
    </>
  },
];
...
{listItemContent.map(item => (
  <ListItem key={item.key}>
    <h1>{item.title}</h1>
    <p>{item.content}</p>
  </ListItem>
))}

Note that you should ideally also add a key to each React element of an array.

You might want to use react's dangerouslySetInnerHTML

{listItemContent.map(item => (
   <ListItem key={item.key}>
   <h1>{item.title}</h1>
   <p dangerouslySetInnerHTML={{__html: item.content}} />
   </ListItem>
))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM