πͺ React
We used to have a whole module for React
- React
- π¬ JSX syntactic sugar
- π Embedding JavaScript
- π π³ Fetching data with Effects
- π Fetching data
- π¨πΌβπ¨ Rendering
- π Pokedex
- π Working with forms
- π¦ Props
- π Keys
- π React Router
- π’ Importing and Exporting
- π¦ State
- Team Project
- Vite
- ποΈ Forms with multiple fields
- π€ΉπΌ Synchronising with effects
- π¦»πΌ Handling events
- 𧩠Components
- πͺ What is React
- πͺ Re-Rendering
- πͺ€ Controlled Components
React block viewer
This block viewer lets you flick through all the existing blocks in the React folder so you can choose what parts to add to your pages and what parts you might want to create, revise, or leave out.
It's literally just an alphabetical list of whatever is in this folder.
π¬ JSX syntactic sugar
Learning Objectives
React Learn
π§ Think back to your filterFilms project.
We used <template>
tags to store a plan of the HTML for our component. React uses a similar idea, but instead of <template>
tags, it uses JSX.
Check your understanding
Q: What is JSX in React?
A: It's a mix of JavaScript and HTML used in React components.Q: What are some rules for writing JSX?
A: Wrap elements in a single root, close all tags, and use camelCase for attributes.π Embedding JavaScript
Learning Objectives
React Learn
There are many template languages. Some common ones are Handlebars, EJS, Jinja, Liquid, Go html/template and Twig. Once you understand one, the others are easier to pick up.
Check your understanding
Q: How do you use JavaScript in JSX?
A: Use curly braces {} to include variables, functions, or objects.Q: What is one use of curly braces in JSX?
A: To include JavaScript variables or functions in JSX.π π³ Fetching data with Effects
Learning Objectives
React Learn
π Fetching data
Learning Objectives
Often when you create a React app, you will want to fetch data from an API and display it inside your components. How do we do this in React?
You might think that we could just fetch the data in the component like this, but unfortunately it won’t work. Try it out in the CodeSandbox below.
This is because React is synchronous, while fetch
is asynchronous. If we look in the console, we’ll see that the imgSrc
will always be null when we try to render it. React will try to render before fetch
has had time to get the data from the API.
So how do we fix this? We need to use a React hook called useEffect
.
π¨πΌβπ¨ Rendering
Learning Objectives
React Learn
Here we return to control flow, that we learned about back in JS1. Search “conditionality” to remind yourself of the basics.
React Learn
Here is our friend the map()
function again! We can use it to render a list of items in React.
Check your understanding
Q: How do you render a list of components in React?
A: Use JavaScript's map() method to create components from an array.Q: What does conditional rendering mean in React?
A: Use if statements, &&, or ? : operators in JSX.π Pokedex
Learning Objectives
π Working with forms
Learning Objectives
Modern web applications often involve interacting with forms such as creating an account, adding a blog post or posting a comment. We need to declare form inputs and get the values entered by users to do something with it (like display them on a page or send them in a POST request). So, how do we do this in React?
A popular pattern for building forms and collect user data is the controlled component pattern. A pattern is a repeated solution to a problem that is useful in multiple similar cases. Let’s have a look at an example:
We’re controlling the value of the input by using the value from the reminder state. This means that we can only change the value by updating the state. It is done using the onChange
attribute and the handleChange
function, called every time the input value changes. This happens when a new character is added or removed.
If we didn’t call setReminder
in the handleChange
function, then the input’s value would never change. It would appear as if you couldn’t type in the input!
Finally, the value we keep in the reminder state is displayed on the screen as today’s reminder.
(We could have also transformed the string before we set it with setReminder
, by calling toUpperCase()
on the string.)
π¦ Props
Learning Objectives
React Learn
π§ Think back to your filterFilms project.
We used
createCard()
function. React uses a similar idea.
Check your understanding
Q: What are props in React?
A: Props are values passed from a parent component to a child component.Q: How do you pass a prop to a component?
A: Add the prop to the JSX tag of the child component.π Keys
Learning Objectives
React Learn
β οΈ Keys
Check your understanding
Q: Why are keys important in React's list rendering?
A: Keys help React track and update list items efficiently.Q: What should a key in a React list be like?
A: A key should be stable, predictable, and unique for each list item.π React Router
Learning Objectives
You’ve learned how to build applications with React. The different applications and examples were all built on a single page. What if you wanted to have different pages? with each page having its own URL? You will need to introduce a router in your application.
In JavaScript, a router is the piece of code which is in charge of switching between views of your application and keep each view in sync with a specific URL. For example, you could imagine having a homepage reachable from the root path / and a users page with the path /users.
You can use a framework like Next.js or Remix, write this yourself, or use a library. In React, a popular library to help you achieve this is React Router.
React Learn
Set a timer and stop working on this tutorial after 60 minutes. Write down your blockers and come to class with questions.
π’ Importing and Exporting
Learning Objectives
React Learn
π§ Think back to your Components workshop.
We exported functions to use in other files using modules. You can export your React components in the same way. A React component is a function, so you can export it like any other function.
Check your understanding
Q: What are default and named exports in React?
A: They are ways to export components from a file for use in other files.Q: Why split components into different files?
A: For better organization and to reuse components easily.π¦ State
Learning Objectives
React Learn
π§ Search for “state” in the curriculum
Fun fact, you first met the concept of state in CYF Blocks
Check your understanding
Q: What is the role of state in a React component?
A: State lets components remember information between renders.
Q: How do you use state in a React component?
A: Employ the useState
Hook to create a state variable and a setter function.
Team Project
Learning Objectives
In this module you are working in a team to build a React app. (You should have created your group already.)
Take this opportunity to work with your team on your React app. You can use this time to work on your app, to discuss your app with your team, ask questions and get help with blockers.
You can use any study group time to work on your product.
Vite
Learning Objectives
Vite is a build tool. It is the default build tool for Vue, SvelteKit, Preact and Solid. It is a common build tool for React and we will use it in this course.
In your terminal, run:
npm create vite@latest
And choose these options:
# Project name (you will need to type this):
react-vite
# Select a framework (use the Up/Down arrow keys to navigate):
React
# Select a variant (use the Up/Down arrow keys to navigate):
JavaScript + SWC
Change into the new directory and start the development server:
cd react-vite
npm install
npm run dev
π‘ Create React App
create-react-app
. This is no longer maintained or recommended by the React team. It is still used in many tutorials and examples, but it is not the best way to start a new React project nowadays.ποΈ Forms with multiple fields
Learning Objectives
Let’s have a look at a more complex example. Here we will build a form for users to create a personal account. Make sure to select CreateAccountForm.js
in the menu to you’re looking at the right part of the code.
We now have three different inputs named username
, email
and password
. There is a corresponding state variable and change handler function for each value.
π§Ό Inlining event handlers
We could make our code a bit shorter if we inlined our event handlers:
π§Ί Centralising event handlers
Sometimes we need to put all of our update logic in one function. Maybe we need to validate the user’s input before we set it in state.
We can use a single handleChange
function, that is reused to keep track of changes for all of the form fields. To be able to tell which <input>
is being updated, we check the event.target.name
field. This corresponds to the name attribute on the <input>
(e.g. <input name="username">
).
Based on this value, we then decide which state to update:
π€ΉπΌ Synchronising with effects
Learning Objectives
React Learn
Effect here means “side effect”. We use the useEffect()
hook to run code that has side effects, like fetching data from an API. We use these sparingly, because they can make our code harder to reason about.
Check your understanding
Q: What is the purpose of the useEffect hook in React?
A: It's used for handling side effects in components, like synchronising with external systems.Q: What's the difference between effects and events in React?
A: Effects handle side effects after a component renders, while events handle user interactions within a component.π‘
Use Effects Sparingly
π¦»πΌ Handling events
Learning Objectives
React Learn
π§ Think back to JS2 where you learned how to handle Events
Check your understanding
Q: How do you attach an event handler to a JSX element in React?
A: By passing the handler function as a prop, like onClick={handleClick}
.
Q: What is a common mistake when attaching event handlers in JSX?
A: Accidentally calling the function (onClick={handleClick()})
instead of passing it.
𧩠Components
Learning Objectives
React Learn
React organises the code for a component into a single folder, and sometimes a single file. Everything that belongs to the component: styles, tests, etc, is in one place. This is a convention, not a requirement, but it’s a good one to follow.
Check your understanding
What is a React component?
Like any component, a React component is a self-contained piece of code that can be reused in different places.How do you make one?
You write a JavaScript function that returns JSX.πͺ What is React
Learning Objectives
React is a widely used JavaScript library for building user interfaces.
To write good React code, you must learn to think in React. Luckily for you, you have been learning JavaScript in a
Let’s start by exploring React Learn, the official docs for React.
πͺ Re-Rendering
Learning Objectives
React Learn
Check your understanding
Q: What are the three steps in displaying a React component?
A: Triggering a render, rendering the component, and committing to the DOM
Q: Why is rendering considered a pure calculation in React?
A: Because it should not change any objects or variables and always produce the same output for the same inputs.