2.4 KiB
id | title | layout | permalink | prev | next |
---|---|---|---|---|---|
jsx-gotchas | JSX Gotchas | docs | jsx-gotchas.html | jsx-in-depth.html | interactivity-and-dynamic-uis.html |
JSX looks like HTML but there are some important differences you may run into.
Note:
For DOM differences, such as the inline
style
attribute, check here.
Whitespace Removal
JSX doesn't follow the same whitespace elimination rules as HTML. JSX removes all whitespace between two curly braces expressions. If you want to have whitespace, simply add {' '}
.
<div>{this.props.name} {' '} {this.props.surname}</div>
Follow Issue #65 for discussion on this behavior.
HTML Entities
You can insert HTML entities within literal text in JSX:
<div>First · Second</div>
If you want to display an HTML entity within dynamic content, you will run into double escaping issues as React escapes all the strings you are displaying in order to prevent a wide range of XSS attacks by default.
// Bad: It displays "First · Second"
<div>{'First · Second'}</div>
There are various ways to work-around this issue. The easiest one is to write unicode character directly in Javascript. You need to make sure that the file is saved as UTF-8 and that the proper UTF-8 directives are set so the browser will display it correctly.
<div>{'First · Second'}</div>
A safer alternative is to find the unicode number corresponding to the entity and use it inside of a JavaScript string.
<div>{'First \u00b7 Second'}</div>
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
You can use mixed arrays with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
As a last resort, you always have the ability to insert raw HTML.
<div dangerouslySetInnerHTML={{'{{'}}__html: 'First · Second'}} />
Custom HTML Attributes
If you pass properties to native HTML elements that do not exist in the HTML specification, React will not render them. If you want to use a custom attribute, you should prefix it with data-
.
<div data-custom-attribute="foo" />
Web Accessibility attributes starting with aria-
will be rendered properly.
<div aria-hidden={true} />