Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape Curly Brackets in props.children

I'm trying to pass a Handlebars template to be processed as this.props.children using the following JSX snippet:

<MyComponent>
  My address is {{address}}.
</MyComponent>

The result is Uncaught ReferenceError: address is not defined.

A workaround was to use something like:

<MyComponent>
  <span content="My address is {{address}}."></span>
</MyComponent>

And then use this.props.children.props.content. This is the only way I've found to essentially escape {{address}} being interpreted as interpolation by JSX.

Is there a straightforward way to escape curly braces in JSX?

like image 672
osxi Avatar asked Sep 02 '15 21:09

osxi


People also ask

How do you escape curly braces in Jira?

After entering the curly brace and the macro menu pops up, press the ESC key and the menu will go away leaving the curly brace there.

How do you escape brackets in string?

Note: To escape special characters normally you have to use \. For opening curly bracket { , use one extra, like {{ . For closing curly bracket } , use one extra, }} .

What is the purpose of {} squiggly braces in Java?

Different programming languages have various ways to delineate the start and end points of a programming structure, such as a loop, method or conditional statement. For example, Java and C++ are often referred to as curly brace languages because curly braces are used to define the start and end of a code block.


2 Answers

Try to wrap component content into curly braces:

<MyComponent>
  {"My address is {{address}}."}
</MyComponent>

All content in braces will be an expression and will not be parsed as JSX. At least, it works in Babel REPL

like image 178
just-boris Avatar answered Sep 28 '22 10:09

just-boris


As Template Literals are introduced in ES6, we can use them here without introducing too many curly braces.

render() {
     let address = 'Somewhere on this earth!';
     return (
        <MyComponent>
            {`My address is ${address}`}
        </MyComponent>    
     );
}

Link to JSFiddle

Hope this helps :)

like image 43
Hardik Modha Avatar answered Sep 28 '22 10:09

Hardik Modha