JSX Syntax Stuff
More powerful tricks and some common errors to avoid.
class VS className
You can’t use the word class
in JSX because it is a reserved word in JavaScript. You have to use className
(also case-sensitive)
<h1 className="big"> Hey </h1>
Self-Closing Tags
This includes <br/>
and <img />
which in HTML, it will still work without the slash /
. On the other hand, JSX will raise an error if you don’t include /
in your tag.
Fine in JSX:
<br /> NOT FINE AT ALL in JSX:
<br>
JavaScript in JSX
use {}
to include a JavaScript code in your JSX.
Variable attributes
Object properties are often used to set attributes
Event Listeners
An event listener attributes’s name should start with on
+ the type of event that you’re listening for. The attribute’s value should be a function
In HTML, event listener names are written lowercase onclick
but in JSX, they are in camelCase onClick
Keys
For making a list in JSX. key
is an attribute which React uses them internally to keep track of lists.
If you don’t use key, React might accidentally re-arrange list item into wrong order
Not all lists need to have keys
. A list needs keys
if either of the following are true:
- The list-items have memory from one render to the next. For instance, when a to-do list renders, each item must “remember” whether it was checked off. The items shouldn’t get amnesia when they render.
- A list’s order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.