JSX Rules
There are a few key rules to keep in mind when working with JSX:
- React component names must be capitalized. Names that don’t begin with a capital letter are treated as built-in components.
- JSX allows you to return only one parent element from a given component.
If you need to return multiple HTML elements, wrap them in a single parent tag such as
<div></div>
<React.fragments><React.fragments/>
<></>
, or any semantic tag.
//JSX
const App = () => {
return (
<div>
<h1>Hello World!</h1>
<p>Here is some paragraph text</p>
</div>
);
}
Note that we need to wrap everything we want to return inside the () brackets of return.
- In JSX, every tag, must be closed. There are some instances where it may be tedious to rewrite a closing tag, especially when there is nothing in it…such as an
<img>
tag…here we use self closing tags<img />
instead. - Since JSX is closer to JavaScript than HTML, React DOM uses camelCase for HTML attribute names. For example:
tabIndex
,onChange
, and so on. - JavaScript reserves “class” and “for” as keywords, so use “className” and “htmlFor” instead, respectively.