About JSX

Notice in the previous section, when implementing LikeButton, we used an HTML-like string:


<button onClick={() => setLiked(true)}>Like
</button>

The syntax


<Type attribute=value>children</Type>

is an extension to JavaScript and called JSX. JSX can have:

HTML elements or user-defined components as Type. User-defined components must be capitalized.

user-defined props, 'key', 'ref', HTML-attribute (eg. className, checked) as attribute. {...props} copies the entire inherited props list.

string literals, {expression}, {function}, {JSX components} as attribute value. 'checked' is the same as 'checked={true}'.

string literals, {expression}, {function}, or other {JSX components} as children. 'false', 'null', 'undefined', and 'true' are valid children. They simply don't render. Eg. <div/>,<div></div>,<div>{true}</div> render to the same thing.


const msg = 'Hello, world';
const c1 = 'greeting';
const myEventHandler = () => { alert("YES"); }
const element = (
  <h1 className={c1} myProp="a" onClick={myEventHandler}>
    {true && msg}!!!
  </h1>
);

Note that there are no parentheses after 'myEventHandler' specified for 'onClick'.