62

I am having problems displaying { and } as text in React. I saw a similar question that someone said to wrap the entire string in curlies, but this is not working:

let queries_block = this.state.previous_queries.map((dataset) => {
            return (<p>{"{{}}"}<p>)
        });

        if (results) {
            results_block = (
                <div>
                    <p>Queries:</p>
                    {queries_block}
                    <br/><br/>
                    <p>Results: {results_count}</p>
                    <JSONPretty id="json-pretty" json={results}></JSONPretty>
                </div>
            );
        } else {
            results_block = null;
        }

The return (<p>{"{{}}"}<p>) causes

ERROR in ./src/components/app.js
Module build failed: SyntaxError: Unexpected token, expected } (47:13)

  45 |                     <JSONPretty id="json-pretty" json={results}></JSONPretty>
  46 |                 </div>
> 47 |             );
     |              ^
  48 |         } else {
  49 |             results_block = null;
  50 |         }

 @ ./src/index.js 15:11-38
webpack: Failed to compile.

Is there an easy way to escape curly braces in jsx?

vsync
  • 118,978
  • 58
  • 307
  • 400
codyc4321
  • 9,014
  • 22
  • 92
  • 165

4 Answers4

113

If you'd like to render curly braces as plain text within a JSX document simply use the HTML character codes.

Left Curly Brace { : &#123;

Right Curly Brace } : &#125;

Rob LaFave
  • 1,131
  • 1
  • 6
  • 3
70

I think the issue is just a typo. You have this:

return (<p>{"{{}}"}<p>)

but you need this (note the closing p tag instead of another opening one):

return (<p>{"{{}}"}</p>)
user94559
  • 59,196
  • 6
  • 103
  • 103
8

You can even use string interpolation in ES6. Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. Template literals are enclosed by the backtick (` `) (grave accent) character instead of double or single quotes.

eg: return (<p>{`{{}}`}</p>)
sr9yar
  • 4,850
  • 5
  • 53
  • 59
Jeeva
  • 1,550
  • 12
  • 15
8

If you are in a situation where you can't use &#123; and &#125;, then you can use custom code:

export default class Component extends React.Component {
  render () {
    return (
      Some object {'{'}id: 1{'}'}
    )
  }
}

Which will output the text Some object {id: 1}

Update: Changed it to a better solution, thanks to @xec

dreamLo
  • 1,612
  • 12
  • 17