Although JSX tries to be similar to HTML, they have some differences.
In JSX, we write in camelCase all DOM properties and attributes, including event handlers. For instance, the tabindex attribute becomes tabIndex. However, two exceptions to this rule are aria- and data- attributes, which retain their typical spelling as they appear in plain HTML.
htmlFor
Since for is a reserved word in JS, React elements use the htmlFor property.
Escaping
Standard HTML is not entirely secure, as unescaped text can pose a threat. It is necessary to escape any text that should be displayed as plain text, to prevent any HTML within from executing. This situation can be particularly hazardous in cases where the user adds this text to the website.
JSX operates differently. Any output that occurs under normal circumstances is secure by default and is automatically escaped. However, in instances where it is unnecessary, the automatic escaping can be turned off like so:
See the Pen js_react_jsx_html_difference_safety by Hexlet (@hexlet) on CodePen.
You need to use the dangerouslySetInnerHTML property to output without escaping. We pass an object with the __html
property to this property, the value of which is a string with HTML.
If a component has a dangerouslySetInnerHTML attribute, it should have no content. The following example will lead to an error:
<div dangerouslySetInnerHTML={{ __html: '<p>content</p>' }}>more content</div>;
Styles
The style attribute works quite differently. In HTML, it's a plain string. In JSX, it's only an object:
See the Pen js_react_jsx_html_difference_style by Hexlet (@hexlet) on CodePen.
We write CSS property names in camelCase for consistency with attribute names.
Default property value
If we pass a property to a component without a value, it automatically becomes true
.
The examples below are equivalent:
<MyTextBox autoComplete />
<MyTextBox autoComplete={true} />
In this case, the first option is preferable.
The rest
You can read more about the differences in the official documentation. In addition, future lessons will show these differences in practice.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.