kakaja
kakaja

Reputation: 734

Reactjs: How to put HTML into primaryText of a list item?

I would like to have a span inside the ListItem like this:

<ListItem
    primaryText={"<span class='inner'>Some important info</span>" + item.title}
/>

When this is rendered, I don't get an HTML span element, but a text <span class='inner'>Some important info</span>Title of the list item. How to make HTML render as HTML?

Upvotes: 4

Views: 3234

Answers (3)

Eric Hasselbring
Eric Hasselbring

Reputation: 1414

Based on the info given, you should move the span inside the ListItem component and deal with it there rather than passing in the props.

<ListItem
  primaryText={ 'Some important info' } 
  title={ item.title }
/>

  //List Item Component
import React from 'react'

const ListItem = ( props ) => {

  return (
    <li>
      <span className='inner'>{ props.primaryText }</span>{ ` ${props.title}` }
    </li>
  )
}

export default ListItem

Upvotes: 2

Marlonicus
Marlonicus

Reputation: 66

EDIT: Ignore me, just saw you needed it specifically for a ListItem

If you need to render HTML within an element, you can use the dangerouslySetInnerHTML prop (but it comes with some risks, and the name suggests):

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

Docs here: https://facebook.github.io/react/docs/dom-elements.html#dangerouslysetinnerhtml

Upvotes: 2

Mayank Shukla
Mayank Shukla

Reputation: 104479

Remove "" around the span, because when you use " it will get converted into string, it will not be treated as html tag.

Write it like this this:

primaryText={<div>
                <span className='inner'>Some important info</span>
                {item.title}
            </div>}

Note: class is reserved keyword so, to apply css classes use className.

Upvotes: 3

Related Questions