63

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?

0

4 Answers 4

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;

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>)
0
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>)
0
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

1
  • 2
    Why not just Some object {'{'}id: 1{'}'}
    – xec
    Jan 27, 2022 at 12:49

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.