πŸͺ„ React

We used to have a whole module for React

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Writing markup with jsx

🧠 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.

question

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ JavaScript in JSX with Curly Braces

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.

question

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Fetching data with Effects

πŸ• 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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Conditional rendering

Here we return to control flow, that we learned about back in JS1. Search “conditionality” to remind yourself of the basics.

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Rendering lists

Here is our friend the map() function again! We can use it to render a list of items in React.

question

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Passing props to a component

🧠 Think back to your filterFilms project.

We used destructuring 🧢 🧢 destructuring Destructuring unpacks values from arrays or objects into individual variables. to pull out the properties of an object and pass it to our createCard() function. React uses a similar idea.

question

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Keeping list items in order with key

⚠️ warning

JSX elements directly inside a map() call always need keys!

question

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.

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ React Router Getting Started Tutorial

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Importing and exporting components

🧠 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.

question

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

narrative

🧠 Search for “state” in the curriculum

Fun fact, you first met the concept of state in CYF Blocks

question

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

πŸ’‘ tip

The default build tool for React used to be 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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Synchronizing with Effects

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.

question

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.

πŸ’‘ tip

As you build and review your React Hotel apps, use You Probably Don’t Need an Effect to help you critique the code you read.

🦻🏼 Handling events

Learning Objectives

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Responding to Events

🧠 Think back to JS2 where you learned how to handle Events

question

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

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Your first component

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.

question

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 style 🧢 🧢 style You have been learning in a declarative and functional programming style that is very similar to React. You have built components. 🧢 🧢 components. A component is a reusable, self-contained piece of code. Components are like lego blocks you can build websites with. You have built components that are functions. You have passed data into those functions. You have defined state objects. You have mapped over data and returned new arrays of components. You’ve practically learned React already! It’s like we planned this…

Let’s start by exploring React Learn, the official docs for React.

πŸͺž Re-Rendering

Learning Objectives

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Render and Commit

question

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.

πŸͺ€ Controlled Components

Learning Objectives

narrative

Complete πŸ§‘πŸΎβ€πŸŽ“ Reacting to inputs with state

question

Q: What is the difference between controlled and uncontrolled components in React?A: Controlled components are components that are controlled by React, whereas uncontrolled components are controlled by the DOM.
Q: What is the difference between declarative and imperative programming in React?A: Declarative programming in React involves describing the UI state, whereas imperative programming involves directly manipulating the DOM.