React props: Using an HTML entity within JSX dynamic content?

Here are a few options (I outlined these in a more general answer awhile back):

  1. Easiest - Use Unicode

    <MyPanel title={ `${name} – ${description}` } />
    
  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <MyPanel title={`${name} \u2013 ${description}`} />
    

    or

    <MyPanel title={`${name} ${String.fromCharCode(8211)} ${description}`} />
    
  3. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    title={`${name} &ndash; ${description}`}
    

    with:

    <div dangerouslySetInnerHTML={{__html: props.title}}></div>
    

const MyPanel = (props) => {
  return (
    <div>{props.title}</div>
  )
}

const MyPanelwithDangerousHTML = (props) => {
  return (
    <div dangerouslySetInnerHTML={{__html: props.title}}></div>
  )
}

var description = "description";
var name = "name";

ReactDOM.render(<MyPanel title={`${name} – ${description}`} />
, document.getElementById("option1"));

ReactDOM.render(<MyPanel title={`${name} \u2013 ${description}`} />
, document.getElementById("option2"));

ReactDOM.render(<MyPanel title={`${name} ${String.fromCharCode(8211)} ${description}`} />
, document.getElementById("option3"));

ReactDOM.render(<MyPanelwithDangerousHTML title={`${name} &ndash; ${description}`} />
, document.getElementById("option4"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

<div id="option1"></div>
<div id="option2"></div>
<div id="option3"></div>
<div id="option4"></div>

You can avoid the superfluous span with a Fragment:

<MyPanel title={<>{name} &ndash; {description}</>} ... </MyPanel>

This feature was introduced in React 16.2.

See the Documentation


I agree with @samanime that using the actual character is best for simple cases, but if your content is truly dynamic, I would prefer using a Fragment over either the entityToChar or dangerouslySetInnerHTML approaches.