React cheat sheet
96 one-line examples for React. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.
JSX Basics
| Code | What it does |
|---|---|
<h1>Hello</h1> | JSX looks like HTML inside JavaScript. |
const el = <p>Hi</p> | Assign JSX to a variable. |
return <div>Text</div> | A component returns JSX. |
<div className="box" /> | Use className, not class, for CSS. |
<img src={url} /> | Curly braces insert JavaScript values. |
<p>{name}</p> | Curly braces show a variable in JSX. |
<p>{2 + 3}</p> | Curly braces run simple expressions. |
<input disabled /> | A bare attribute means true. |
<br /> | Empty tags need a closing slash. |
<>text</> | A fragment groups elements without a wrapper. |
{cond && <p>Yes</p>} | Show an element only when cond is true. |
{items.map(render)} | Curly braces can hold a function call. |
Components
| Code | What it does |
|---|---|
function App() { } | Define a component as a function. |
function App() { return <p/> } | A component must return JSX. |
<App /> | Render a component with a self-closing tag. |
<App /> | Component names start with a capital letter. |
export default App | Export the component for other files. |
import App from './App' | Import a component from its file. |
export function Card() {} | Use a named export for a component. |
import { Card } from './Card' | Import a named export with braces. |
function App(props) {} | A component receives props as an argument. |
<Card title="Hi" /> | Pass a prop with an attribute. |
props.title | Read a prop value from the props object. |
{props.children} | Children pass nested content into a component. |
State with useState
| Code | What it does |
|---|---|
import { useState } from 'react' | Import the useState hook first. |
const [n, setN] = useState(0) | Create state with a value and setter. |
setN(5) | Call the setter to change state. |
setN(n + 1) | Use the current value to compute the next. |
setN(prev => prev + 1) | Use a function when the next value depends on the old. |
const [on, setOn] = useState(false) | State can hold a boolean. |
const [s, setS] = useState('') | State can hold a string. |
const [a, setA] = useState([]) | State can hold an array. |
setA([...a, item]) | Copy the array before you add an item. |
setA(a.filter(x => x !== id)) | Copy the array to remove an item. |
setUser({...u, name: 'A'}) | Copy the object before you change a field. |
useState(0) | The argument sets the first value. |
Events
| Code | What it does |
|---|---|
<button onClick={go}>Go</button> | Attach a handler with onClick. |
onClick={() => setN(n + 1)} | Use an arrow function to call a setter. |
onClick={handleClick} | Pass the function, do not call it. |
onClick={() => go(id)} | Wrap a call with arguments in an arrow function. |
onChange={e => setV(e.target.value)} | Read an input value from the event. |
onSubmit={handleSubmit} | Handle form submit with onSubmit. |
e.preventDefault() | Stop the browser from reloading the page. |
onKeyDown={onKey} | Listen for key presses on an element. |
onMouseEnter={onEnter} | Listen for the mouse entering an element. |
onFocus={onFocus} | Run code when an input gets focus. |
function go(e) {} | The handler receives the event object. |
e.target.value | Get the value of the input that fired. |
Lists and Keys
| Code | What it does |
|---|---|
items.map(i => <li>{i}</li>) | Map an array to a list of elements. |
items.map(i => <li key={i.id}/>) | Add a key to each list item. |
key={item.id} | Use a stable id as the key. |
key={index} | Use the index only as a last resort. |
{items.map(render)} | Wrap the map call in curly braces. |
{items.length === 0 && <p>Empty</p>} | Show a message when the list is empty. |
items.filter(x => x.on) | Filter the array before you render it. |
[...items, newItem] | Add an item with a new array. |
items.slice().sort() | Copy before you sort the array. |
<ul>{list}</ul> | Put list elements inside a ul. |
<li key={id}>{name}</li> | Each item needs a unique key. |
{items.map(Item)} | Pass a component to map to render items. |
Effects with useEffect
| Code | What it does |
|---|---|
import { useEffect } from 'react' | Import the useEffect hook first. |
useEffect(() => {}, []) | Run the effect once after the first render. |
useEffect(() => {}) | Run the effect after every render. |
useEffect(() => {}, [id]) | Run the effect when id changes. |
useEffect(() => { load() }, []) | Fetch data when the component mounts. |
return () => clear() | Return a cleanup function from the effect. |
useEffect(() => { t = set() }, []) | Set up a timer when the component mounts. |
useEffect(() => { return () => clear() }, []) | Clear the timer when the component unmounts. |
document.title = name | Change the page title inside an effect. |
useEffect(() => { sub() }, []) | Subscribe to a source on mount. |
useEffect(() => {}, [a, b]) | List every value the effect uses. |
useEffect(() => { save(v) }, [v]) | Save a value when it changes. |
Conditional Rendering
| Code | What it does |
|---|---|
{on && <p>On</p>} | Render an element only when on is true. |
{on ? <A/> : <B/>} | Choose one of two elements. |
{on ? 'Yes' : 'No'} | Choose one of two strings. |
{!on && <p>Off</p>} | Render when the value is false. |
{count > 0 && <p>{count}</p>} | Render only when the count is above zero. |
if (!user) return null | Return null to render nothing. |
if (loading) return <Spinner/> | Return early while data loads. |
{items.length && <List/>} | A zero length hides the element. |
{items.length > 0 && <List/>} | Compare with zero to avoid a stray 0. |
{user?.name} | Optional chaining guards a missing value. |
{name ?? 'Guest'} | Use a fallback when the value is null. |
{on ? <A/> : null} | Return null to show nothing. |
Forms and Inputs
| Code | What it does |
|---|---|
<input value={v} /> | Bind an input value to state. |
onChange={e => setV(e.target.value)} | Update state on each keystroke. |
<input value={v} onChange={set} /> | A controlled input needs value and onChange. |
<textarea value={v} /> | A textarea also uses value and onChange. |
<select value={v} onChange={set}> | A select uses value and onChange. |
<input type="checkbox" checked={c} /> | A checkbox uses checked, not value. |
<form onSubmit={save}> | Handle the form submit with onSubmit. |
e.preventDefault() | Stop the page reload on submit. |
<label htmlFor="name">Name</label> | Use htmlFor to link a label to an input. |
<input id="name" name="name" /> | Give the input a matching id. |
<input required /> | The browser checks required fields. |
setV('') | Reset the input value after submit. |