JSX Syntax Stuff

Penny Pang
path2code
Published in
2 min readDec 17, 2018

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.

This will evaluate 2+3=5 instead of return a string of “2+3”
Or inserting variables inside JSX

Variable attributes

Object properties are often used to set attributes

the { } are used to get the JavaScript pics object where all the links of the images are stored.

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

always using { } to call a JavaScript 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:

  1. 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.
  2. A list’s order might be shuffled. For instance, a list of search results might be shuffled from one render to the next.

--

--

Penny Pang
path2code

Full-time UX/UI Designer, Part-time online entrepreneur, Casual food blogger and innovation advocate