21/7/23, 11:44 PM
Cheatsheets / Introduction to React
JSX
JSX className
In JSX, you can’t use the word class ! You have to // When rendered, this JSX
use className instead. This is because JSX
expression...
gets translated into JavaScript, and class is a
reserved word in JavaScript.
const heading = <h1 className="large-
When JSX is rendered, JSX className heading">Codecademy</h1>;
attributes are automatically rendered as class
attributes.
// ...will be rendered as this HTML
<h1 class="large-
heading">Codecademy</h1>
JSX and conditional
In JSX, && is commonly used to render an element // All of the list items will display
based on a boolean condition. && works best in
if
conditionals that will sometimes do an action, but
other times do nothing at all. // baby is false and age is above 25
If the expression on the left of the && evaluates as const tasty = (
true, then the JSX on the right of the && will be <ul>
rendered. If the !rst expression is false, however,
<li>Applesauce</li>
then the JSX to the right of the && will be ignored
and not rendered. { !baby && <li>Pizza</li> }
{ age > 15 && <li>Brussels
Sprouts</li> }
{ age > 20 && <li>Oysters</li> }
{ age > 25 && <li>Grappa</li> }
</ul>
);
about:srcdoc Page 1 of 7
21/7/23, 11:44 PM
JSX conditionals
JSX does not support if/else syntax in embedded // Using ternary operator
JavaScript. There are three ways to express
conditionals for use with JSX elements:
const headline = (
1. a ternary within curly braces in JSX <h1>
2. an if statement outside a JSX element, or { age >= drinkingAge ? 'Buy Drink'
3. the && operator.
: 'Do Teen Stuff' }
</h1>
);
// Using if/else outside of JSX
let text;
if (age >= drinkingAge) { text = 'Buy
Drink' }
else { text = 'Do Teen Stuff' }
const headline = <h1>{ text }</h1>
// Using && operator. Renders as empty
div if length is 0
const unreadMessages = [ 'hello?',
'remember me!'];
const update = (
<div>
{unreadMessages.length > 0 &&
<h1>
You have
{unreadMessages.length} unread
messages.
</h1>
}
</div>
);
about:srcdoc Page 2 of 7
21/7/23, 11:44 PM
Embedding JavaScript code in JSX
Any text between JSX tags will be read as text <p>{ Math.random() }</p>
content, not as JavaScript. In order for the text to be
read as JavaScript, the code must be embedded
between curly braces { } . // Above JSX will be rendered something
like this:
<p>0.88</p>
JSX element event listeners
In JSX, event listeners are speci!ed as attributes on // Basic example
elements. An event listener attribute’s name should
const handleClick = () => alert("Hello
be written in camelCase, such as onClick for an
onclick event, and onMouseOver for an world!");
onmouseover event.
An event listener attribute’s value should be a const button = <button onClick=
function. Event listener functions can be declared
{handleClick}>Click here</button>;
inline or as variables and they can optionally take
one argument representing the event.
// Example with event parameter
const handleMouseOver = (event) =>
event.target.style.color = 'purple';
const button2 = <div onMouseOver=
{handleMouseOver}>Drag here to change
color</div>;
Setting JSX attribute values with embedded JavaScript
When writing JSX, it’s common to set attributes const introClass = "introduction";
using embedded JavaScript variables.
const introParagraph = <p className=
{introClass}>Hello world</p>;
about:srcdoc Page 3 of 7
21/7/23, 11:44 PM
JSX .map() method
The array method map() comes up often in const strings = ['Home', 'Shop', 'About
React. It’s good to get in the habit of using it
Me'];
alongside JSX.
If you want to create a list of JSX elements from a
given array, then map() over each element in the const listItems = strings.map(string =>
array, returning a list item for each one.
<li>{string}</li>);
<ul>{listItems}</ul>
JSX empty elements syntax
In JSX, empty elements must explicitly be closed <br />
using a closing slash at the end of their tag:
<img src="example_url" />
<tagName /> .
A couple examples of empty element tags that must
explicitly be closed include <br> and <img> .
React.createElement() Creates Virtual DOM Elements
The React.createElement() function is // The following JSX...
used by React to actually create virtual DOM
const h1 = <h1 className="header">Hello
elements from JSX. When the JSX is compiled, it is
replaced by calls to world</h1>;
React.createElement() .
You usually won’t write this function yourself, but it’s
// ...will be compiled to the
useful to know about.
following:
const h1 = React.createElement(
'h1',
{
className: 'header',
},
'Hello world'
);
about:srcdoc Page 4 of 7
21/7/23, 11:44 PM
JSX key attribute
In JSX elements in a list, the key attribute is used <ul>
to uniquely identify individual elements. It is
<li key="key1">One</li>
declared like any other attribute.
Keys can help performance because they allow <li key="key2">Two</li>
React to keep track of whether individual list items <li key="key3">Three</li>
should be rendered, or if the order of individual
<li key="key4">Four</li>
items is important.
</ul>
Nested JSX elements
In order for the code to compile, a JSX expression const myClasses = (
must have exactly one outermost element. In the
<a href="https://www.codecademy.com">
below block of code the <a> tag is the outermost
element. <h1>
Sign Up!
</h1>
</a>
);
JSX Syntax and JavaScript
JSX is a syntax extension of JavaScript. It’s used to import React from 'react';
create DOM elements which are then rendered in
the React DOM.
import { createRoot } from 'react-
A JavaScript !le containing JSX will have to be dom/client';
compiled before it reaches a web browser. The code
block shows some example JavaScript code that will
need to be compiled.
const container =
document.getElementById('app');
const root = createRoot(container);
root.render(<h1>Render me!</h1>);
about:srcdoc Page 5 of 7
21/7/23, 11:44 PM
Multiline JSX Expression
A JSX expression that spans multiple lines must be const myList = (
wrapped in parentheses: ( and ) . In the example
<ul>
code, we see the opening parentheses on the same
line as the constant declaration, before the JSX <li>item 1</li>
expression begins. We see the closing parentheses <li>item 2</li>
on the line following the end of the JSX expression.
<li>item 3</li>
</ul>
);
JSX syntax and HTML
In the block of code we see the similarities between const title = <h1>Welcome all!</h1>
JSX syntax and HTML: they both use the angle
bracket opening and closing tags ( <h1> and
</h1> ).
When used in a React component, JSX will be
rendered as HTML in the browser.
JSX attributes
The syntax of JSX attributes closely resembles that const example = <h1 id="example">JSX
of HTML attributes. In the block of code, inside of
Attributes</h1>;
the opening tag of the <h1> JSX element, we see
an id attribute with the value "example" .
ReactDOM JavaScript library
The JavaScript library react-dom/client import React from 'react';
contains the createRoot() method, which is
import { createRoot } from 'react-
used to create a React root at the HTML element
used as an argument. The React root renders JSX dom/client';
elements to the DOM by taking a JSX expression,
creating a corresponding tree of DOM nodes, and
const container =
adding that tree to the DOM.
The code example begins by creating a React root at document.getElementById('app');
the HTML element with the id app and storing it in const root = createRoot(container);
root . Then, using root ‘s render()
method, the JSX used as an argument is rendered.
root.render(<h1>This is an example.
</h1>);
about:srcdoc Page 6 of 7
21/7/23, 11:44 PM
Embedding JavaScript in JSX
JavaScript expressions may be embedded within JSX let expr = <h1>{10 * 10}</h1>;
expressions. The embedded JavaScript expression
must be wrapped in curly braces.
// above will be rendered as
In the provided example, we are embedding the <h1>100</h1>
JavaScript expression 10 * 10 within the
<h1> tag. When this JSX expression is rendered to
the DOM, the embedded JavaScript expression is
evaluated and rendered as 100 as the content of
the <h1> tag.
The Virtual Dom
React uses Virtual DOM, which can be thought of as
a blueprint of the DOM. When any changes are made
to React elements, the Virtual DOM is updated. The
Virtual DOM !nds the di'erences between it and the
DOM and re-renders only the elements in the DOM
that changed. This makes the Virtual DOM faster and
more e(cient than updating the entire DOM.
Print Share
about:srcdoc Page 7 of 7