Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML entities inside a string in React

I'm facing issue while displaying curly quotes HTML entities in React JS. Ref straight and curly quotes

    render() {
      return (
              <h4>
              {theme == 'blue' && 'This is sample text'}
              {theme == 'red' && 'What&rsquo;s your role in this project'}
              </h4>
            )
         }

Current Output

What&rsquo;s your role in this project

Expected Output
What’s your role in this project

I don't want to use dangerouslySetInnerHTML or i don't want to define these values in react state property. Thanks in advance.

like image 754
Praveen M P Avatar asked Mar 23 '26 12:03

Praveen M P


2 Answers

Using the String.fromCharCode method:

Check React docs : https://shripadk.github.io/react/docs/jsx-gotchas.html

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode

To Find the char code: http://www.mauvecloud.net/charsets/CharCodeFinder.html

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What ${String.fromCharCode(8217}s your role in this project`}
                  </h4>
                )
             }

template literals `` for the text

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && `What’s your role in this project`}
                  </h4>
                )
             }

Using double quotes and single quotes

render() {
          return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && "What’s your role in this project"}
                  </h4>
                )
             }

Use escape character

 return (
                  <h4>
                  {theme == 'blue' && 'This is sample text'}
                  {theme == 'red' && 'What \’s your role in this project'}
                  </h4>
                )
             } 
like image 72
Dhanuka Perera Avatar answered Mar 26 '26 00:03

Dhanuka Perera


If you really can't use " or template strings, try returning a fragment

<>What&rsquo;s your role in this project</>
like image 34
n9iels Avatar answered Mar 26 '26 01:03

n9iels