JSX - ryantc94/Knights-of-Arthur GitHub Wiki
- You can embed any JavaScript expression in JSX by wrapping it in curly braces {}.
- "" and {js} can be used for attributes
- JSX can be line separated, however when doing this, it is recommended to wrap it in parentheses to avoid the pitfalls of automatic semicolon insertion.
- JSX evaluates to JS objects (which is why it can be stored as a JS variable)
- JSX is compiled down to React.CreateElement()
- Basically React.CreateElement creates code like this (this is why you need to import React when using JSX)
//JSX [JSX Part ..............]
const element = <div name="hi"> hi </div>
//React.CreateElement [children will be null if no children]
const element = React.CreateElement("hi", {className:"hi"} ,"hi")
//Output of Both (React Element)
const element = {type: 'h1', props: {className: "hi", children: "hi"}};
- When a JSX tag is capitalized it indicates that it is a React Component i.e
- ^ That is why components must be capitalized
- JSX tag also recognizes dot notation i.e <Component.Child />, but not bracket notation i.e <Component[x]> (it doesn't recognize JS expressions)
- Props default to true if not given a value i.e the require in forms
- Props can be passed as a spread operator and de-structuring can prevent certain props from being passed
const props = {}
const element = <Component {...props} />
const props = {x, ...other}
const element = <Component {...other} />
- Content between JSX opening and closing tags is placed in special props: 'props.children' This special children props can be used as a pattern for React to not have to pass a bunch of props through a parent to get to a child
- JSX removes white space
- {} allows JS expressions to be JSX children as well so you can do stuff like this
function Item(props) {
return <li>{props.message}</li>;
}
function TodoList() {
const todos = ['finish doc', 'submit pr', 'nag dan to review'];
return (
<ul>
{todos.map((message) => <Item key={message} message={message} />)}
</ul>
);
}
-
JSX can take calls backs such as for handling events (well a callback is just a function expression so... kinda reasonable)
-
{true}, {false}, {undefined}, and {null} are not rendered but falsey values such as '0' are, so make sure in conditional rendering to convert to boolean, and if you want the actual word to make it a String()
-
React render can also return an array of elements (???)
-
JSX Prevents Injection Attacks ... huh look into this
-
HTML unescaped?