The React For Absolute Beginners Cheatsheet
The React For Absolute Beginners Cheatsheet
Cheatsheet
React Basics
What is React, really?
React is officially defined as a "JavaScript library for creating user interfaces," but
what does that really mean?
The most basic JavaScript concepts you should be familiar with are variables, basic
data types, conditionals, array methods, functions, and ES modules.
How do I learn all of these JavaScript skills? Check out the comprehensive guide to
learn all of the JavaScript you need for React.
JavaScript is a 20+ year old language which was created for adding small bits of
behavior to the browser through scripts and was not designed for creating complete
applications.
In other words, while JavaScript was used to create React, they were created for
very different purposes.
You can use any browser or window API, such as geolocation or the fetch API.
Also, since React (when it is compiled) runs in the browser, you can perform
common JavaScript actions like DOM querying and manipulation.
3. Creating a React app on your computer using a tool like Create React App
If you want to create a complete web application that you want to ultimately push to
the web, it is best to create that React application on your computer using a tool like
Create React App.
If you are interested in creating React apps on your computer, check out the
complete guide to using Create React App.
The easiest and most beginner-friendly way to create and build React apps for
learning and prototyping is to use a tool like CodeSandbox. You can create a new
React app in seconds by going to react.new!
JSX Elements
JSX is a powerful tool for structuring applications
JSX is meant to make create user interfaces with JavaScript applications easier.
JSX borrows its syntax from the most widely used programming language: HTML
<div>Hello React!</div>
Attributes that consist of multiple words are written in the camel-case syntax
(i.e. className ) and have different names than standard HTML ( class ).
<div id="header">
<h1 className="title">Hello React!</h1>
</div>
The reason JSX has this different way of writing attributes is because it is actually
made using JavaScript functions (more on this later).
Once again, the style properties that we use must be written in the camel-case
style.
<h1 style={{ color: "blue", fontSize: 22, padding: "0.5em 1em" }}>
Hello React!
</h1>;
Style properties that accept pixel values (like width, height, padding,
margin, etc), can use integers instead of strings. For
example, fontSize: 22 instead of fontSize: "22px"
One simple example if that to conditionally hide or display JSX content, we can use
any valid JavaScript conditional, like an if statement or switch statement.
if (isAuthUser) {
return <div>Hello user!</div>
} else {
return <button>Login</button>
}
Where are we returning this code? Within a React component, which we will cover
in a later section.
Both pieces of code will have the same output of "Hello React".
To write JSX and have the browser understand this different syntax, we must use
a transpiler to convert JSX to these function calls.
Components
What are React components?
Instead of just rendering one or another set of JSX elements, we can include them
within React components.
Components are created using what looks like a normal JavaScript function, but is
different in that it returns JSX elements.
function Greeting() {
return <div>Hello React!</div>;
}
Think of React components as our custom React elements that have their own
functionality.
As we know, functions allow us to create our own functionality and reuse it where
we like across our application.
Components are reusable wherever we like across our app and as many times as
we like.
function Greeting() {
return <div>Hello React!</div>;
}
We use the React import to parse the JSX and ReactDOM to render our component to
a root element with the id of "root."
function Greeting() {
if (isAuthUser) {
return "Hello again!";
} else {
return null;
}
}
Another rule is that JSX elements must be wrapped in one parent element. Multiple
sibling elements cannot be returned.
If you need to return multiple elements, but don't need to add another element to
the DOM (usually for a conditional), you can use a special React component called
a fragment.
Fragments can be written as <></> or when you import React into your file,
with <React.Fragment></React.Fragment> .
if (isAuthUser) {
return (
<>
<h1>Hello again!</h1>
<button>Logout</button>
</>
);
} else {
return null;
}
}
function App() {
return (
<Layout>
<Navbar />
<Main />
<Aside />
<Footer />
</Layout>
);
}
What is powerful about this is that we are using the customization of components to
describe what they are (i.e. Layout) and their function in our application. This tells
us how they should be used just by looking at their name.
Additionally, we are using the power of JSX to compose these components. In other
words, to use the HTML-like syntax of JSX to structure them in an immediately
understandable way (i.e. the Navbar is at the top of the app, the Footer at the
bottom, etc).
There are a few core rules to using dynamic values within JSX, however.
JSX can accept any primitive values (strings, booleans, numbers), but it will not
accept plain objects.
For example, conditionals can be included within JSX using the ternary operator,
since it resolves to a value.
function Greeting() {
const isAuthUser = true;
Props
Components can be passed values using props
Data passed to components in JavaScript are called props
Props look identical to attributes on plain JSX/HTML elements, but you can access
their values within the component itself
ReactDOM.render(
<Greeting username="John!" />,
document.getElementById("root")
);
function Greeting(props) {
return <h1>Hello {props.username}</h1>;
}
Another way to say this is that props should never be mutated, since props are a
plain JavaScript object
Components are consider pure functions. That is, for every input,
we should be able to expect the same output. This means we
cannot mutate the props object, only read from it.
The children prop is especially useful for when you want the same component (such
as a Layout component) to wrap all other components.
function Layout(props) {
return <div className="container">{props.children}</div>;
}
function AboutPage() {
return (
<Layout>
<About />
<Footer />
</Layout>
);
}
The benefit of this pattern is that all styles applied to the Layout component will be
shared with its child components.
Use the .map() function to convert lists of data (arrays) into lists of elements.
function App() {
const people = ["John", "Bob", "Fred"];
return (
<ul>
{people.map((person) => (
<Person name={person} />
))}
</ul>
Keys are essential for React to be able to keep track of each element that is being
iterated over with the .map() function
React uses keys to performantly update individual elements when their data
changes (instead of re-rendering the entire list)
Keys need to have unique values to be able to identify each of them according to
their key value
function App() {
const people = [
{ id: "Ksy7py", name: "John" },
{ id: "6eAdl9", name: "Bob" },
{ id: "6eAdl9", name: "Fred" },
];
return (
<ul>
{people.map((person) => (
<Person key={person.id} name={person.name} />
))}
</ul>
);
}
We talk about state management, because we need an effective way to keep track
of and update data across our components as our user interacts with it.
To change our application from static HTML elements to a dynamic one that the
user can interact with, we need state.
When a user types into a form, we keep track of the form state in that component.
When we fetch data from an API to display to the user (i.e. posts in a blog), we
need to save that data in state.
When we want to change data that a component is receiving from props, we use
state to change it instead of mutating the props object.
What is a hook? It is very much like a JavaScript function, but can only be used in a
React function component at the top of the component.
We use hooks to "hook into" certain features and useState gives us the ability to
create and manage state.
useState is an example of a core React hook that comes directly from the React
library: React.useState .
function Greeting() {
const state = React.useState("Hello React");
What is returned from useState is an array. To get access to the state variable and
its value, we can use the first value in that array: state[0] .
There is a way to improve how we write this, however. We can use array
destructuring to get direct access to this state variable and call it what we like,
i.e. title .
function Greeting() {
const [title] = React.useState("Hello React");
What if we want to allow our user to update the greeting they see?
If we include a form, a user can type in a new value. However, we need a way to
update the initial value of our title.
function Greeting() {
const [title] = React.useState("Hello React");
return (
<div>
<h1>{title}</h1>
<input placeholder="Update title" />
</div>
);
}
We can do so with the help of the second element in the array that useState
returns. It is a setter function, to which we can pass whatever value we want the
new state to be.
In our case, we want to get the value that is typed into the input when a user is in
the process of typing. We can get it with the help of React events.
The most common props used to handle events are onClick (for click
events), onChange (when a user types into an input), and onSubmit (when a form is
submitted.
To get data about the event when our input is changed, we can add onChange on
input and connect it to a function that will handle the event. This function will be
called handleInputChange :
function Greeting() {
const [title] = React.useState("Hello React");
function handleInputChange(event) {
console.log("input changed!", event);
}
return (
<div>
<h1>{title}</h1>
<input placeholder="Update title" onChange={handleInputChange} />
</div>
);
}
Note that in the code above, a new event will be logged to the
browser's console whenever the user types into the input
Event data is provided to us as an object with many properties which are dependent
upon the type of event.
Whatever we pass to this setter function when we call it will be put in state.
function Greeting() {
const [title, setTitle] = React.useState("Hello React");
function handleInputChange(event) {
setTitle(event.target.value);
}
return (
<div>
<h1>{title}</h1>
<input placeholder="Update title" onChange={handleInputChange} />
</div>
);
}
Using the code above, whatever the user types into the input (the text comes
from event.target.value ) will be put in state using setTitle and displayed within
the h1 element.
What is special about state and why it must be managed with a dedicated hook like
useState is because a state update (such as when we call setTitle causes a re-
render.