React 2020 Cheatsheet Small PDF
React 2020 Cheatsheet Small PDF
function Header(props) {
// we cannot mutate the props object, we can only read
// from it
props.username = “Doug”;
return <h1>Hello {props.username}</h1>;
}
function Layout(props) {
return <div className=”container”>{props.children}</div>;
}
// The children prop is very useful for when you want the same
// component (such as a Layout component) to wrap all other
// components:
function IndexPage() {
return (
<Layout>
<Header />
<Hero />
<Footer />
</Layout>
);
}
function Header() {
const isAuthenticated = checkAuth();
return (
<nav>
<Logo />
{/* if isAuth is true show AuthLinks. If false Login */}
{isAuthenticated ? <AuthLinks /> : <Login />}
{/* if isAuth is true show Greeting. If false nothing */}
{isAuthenticated && <Greeting />}
</nav>
);
}
function Header() {
const isAuthenticated = checkAuth();
return (
<nav>
{isAuthenticated ? (
<>
<AuthLinks />
<Greeting />
</>
) : <Login />}
</nav>
);
}
function App() {
const people = [‘John’, ‘Bob’, ‘Fred’];
// can interpolate returned list of elements in {}
return (
<ul>
{/* we’re passing each array element as props */}
{people.map(person => <Person name={person} />)}
</ul>
);
}
function App() {
const people = [‘John’, ‘Bob’, ‘Fred’];
// If you don’t have ids with your set of data or unique primi-
tive values,
// you can use the second parameter of .map() to get each ele-
ments index
function App() {
const people = [‘John’, ‘Bob’, ‘Fred’];
return (
<ul>
{/* use array element index for key */}
{people.map((person, i) => <Person key={i} name={person} />}
</ul>
);
}
function App() {
function handleChange(event) {
const inputText = event.target.value;
}
function handleSubmit() {
// on click doesn’t usually need event data
}
return (
<div>
<input type=”text” name=”myInput” onChange={handleChange} />
<button onClick={handleSubmit}>Submit</button>
</div>
);
}
function App() {
// the setter fn is always the second destructured value
const [language, setLanguage] = React.useState(“python”);
// the convention for the setter name is ‘setStateVariable’
return (
<div>
<button onClick={() => setLanguage(“javascript”)}>
Change language to JS
</button>
<p>I am now learning {language}</p>
</div>
);
}
function App() {
const [language, setLanguage] = React.useState(“python”);
const [yearsExperience, setYearsExperience] = React.useS-
tate(0);
return (
<div>
<button onClick={() => setLanguage(“javascript”)}>
Change language to JS
</button>
<input
type=”number”
value={yearsExperience}
onChange={e => setYearsExperience(e.target.value)}
/>
<p>I am now learning {language}</p>
<p>I have {yearsExperience} years of experience</p>
</div>
);
}
return (
<div>
<button
onClick={() => setDeveloper({
language: “javascript”,
yearsExperience: 0
})
}
>
Change language to JS
</button>
<input
type=”number”
value={developer.yearsExperience}
onChange={handleChangeYearsExperience}
/>
<p>I am now learning {developer.language}</p>
<p>I have {developer.yearsExperience} years of experience</p>
</div>
);
}
function App() {
const [developer, setDeveloper] = React.useState({
language: “”,
yearsExperience: 0,
isEmployed: false
});
function handleToggleEmployment(event) {
// we get the prev state variable’s value in the parameters
// we can name ‘prevState’ however we like
setDeveloper(prevState => {
// it is essential to return the new state from this
// function
return {
...prevState, isEmployed: !prevState.isEmployed
};
});
}
return (
<button onClick={handleToggleEmployment}>
Toggle Employment Status
</button>
);
}
function App() {
const [colorIndex, setColorIndex] = React.useState(0);
const colors = [“blue”, “green”, “red”, “orange”];
function handleChangeIndex() {
const next = colorIndex + 1 === colors.length ? 0 : color-
Index + 1;
setColorIndex(next);
}
return (
<button onClick={handleChangeIndex}>
Change background color
</button>
);
}
function App() {
...
// now our button doesn’t work no matter how many times we
click it...
useEffect(() => {
document.body.style.backgroundColor = colors[colorIndex];
}, []);
// the background color is only set once, upon mount
return (
<button onClick={handleChangeIndex}>
Change background color
</button>
);
}
function App() {
...
// when colorIndex changes, the fn will run again
useEffect(() => {
document.body.style.backgroundColor = colors[colorIndex];
}, [colorIndex]);
...
}
function MouseTracker() {
const [mousePosition, setMousePosition] = useState({ x: 0, y:
0 });
React.useEffect(() => {
// .addEventListener() sets up an active listener...
window.addEventListener(“mousemove”, event => {
const { pageX, pageY } = event;
setMousePosition({ x: pageX, y: pageY });
});
return (
<div>
<p>X: {mousePosition.x}, Y: {mousePosition.y}</p>
</div>
);
}
// with promises:
function App() {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
// promises work in callback
fetch(endpoint)
.then(response => response.json())
.then(data => setUser(data));
}, []);
}
React.useEffect(() => {
setTimeout(() => {
setTime(JSON.stringify(new Date(Date.now())));
}, 300);
}, [time]);
return (
<div>
<p>The current time is: {time}</p>
<button onClick={inc}>+ {count}</button>
</div>
);
}
function App() {
const [wordIndex, setWordIndex] = useState(0);
const [count, setCount] = useState(0);
const words = [“i”, “am”, “learning”, “react”];
const word = words[wordIndex];
function getLetterCount(word) {
let i = 0;
while (i < 1000000) i++;
return word.length;
}
return (
<div>
<p>
{word} has {letterCount} letters
</p>
<button onClick={handleChangeIndex}>Next word</button>
<p>Counter: {count}</p>
<button onClick={() => setCount(count + 1)}>+</button>
</div>
);
}
function App() {
const [query, setQuery] = React.useState(“react hooks”);
// we can pass useRef a default value
const searchInput = useRef(null);
function handleClearSearch() {
// current references the text input once App mounts
searchInput.current.value = “”;
// useRef can store basically any value in its .current
property
searchInput.current.focus();
}
return (
<form>
<input
type=”text”
onChange={event => setQuery(event.target.value)}
ref={searchInput}
/>
<button type=”submit”>Search</button>
<button type=”button” onClick={handleClearSearch}>
Clear
</button>
</form>
);
}
function App() {
const [user] = React.useState({ name: “Fred” });
return (
{/* we wrap the parent component with provider property */}
{/* we pass data down the computer tree w/ value prop */}
<UserContext.Provider value={user}>
<Main />
</UserContext.Provider>
);
}
function App() {
const [user] = React.useState({ name: “Fred” });
return (
{/* we wrap the parent component with provider property */}
{/* we pass data down the computer tree w/ value prop */}
<UserContext.Provider value={user}>
<Main />
</UserContext.Provider>
);
}
switch (action.type) {
// if action.type has the string ‘LOGIN’ on it
case “LOGIN”:
// we get data from the payload object on action
return { username: action.payload.username, isAuth: true
};
case “SIGNOUT”:
return { username: “”, isAuth: false };
default:
// if no case matches, return previous state
return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, initialState);
function handleLogin() {
dispatch({ type: “LOGIN”, payload: { username: “Ted” } });
}
return (
<>
Current user: {state.username}, isAuthenticated: {state.is-
Auth}
<button onClick={handleLogin}>Login</button>
<button onClick={handleSignout}>Signout</button>
</>
);
}
function useAPI(endpoint) {
const [value, setValue] = React.useState([]);
React.useEffect(() => {
getData();
}, []);
return value;
};
return (
<ul>
{todos.map(todo => <li key={todo.id}>{todo.text}</li>}
</ul>
);
}
function App() {
// this is the only validly executed hook in this component
const [user, setUser] = React.useState(null);
checkAuth();
Visit CodeArtistry