80

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

5 Answers 5

140

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;

Sign up to request clarification or add additional context in comments.

Comments

91

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

1 Comment

I skipped this at first but it's the right answer: just put a regular string inside JSX expression delimiters. <p>{'{braces are fine here}'}</p>.
11

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

1 Comment

I was about to suggest this before I saw your answer. Yet another way is to use JSON.stringify. e.g. <pre>{JSON.stringify(result, null, 4)}</pre> is a quick and dirty way to print JSON.
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 Comment

Why not just Some object {'{'}id: 1{'}'}
1

You can also render curly braces with a variable as well. For example :

const curlyBraces = '{}'; return This is an example for {cusrlyBraces} rendered in JSX 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.