What the front end does
The front end displays data, collects input and talks to the back end through APIs. It should be fast, accessible and work on every screen size.
Fetching data from an API
async function loadTodos() {
const res = await fetch("/api/todos");
const todos = await res.json();
const list = document.querySelector("#todos");
list.innerHTML = "";
todos.forEach(t => {
const li = document.createElement("li");
li.textContent = t.title;
list.appendChild(li);
});
}
loadTodos();Why React?
As apps grow, updating the page by hand becomes hard. React lets you describe the page as components and updates the screen when data changes.
A React component
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
export default Counter;- A component is a function that returns UI.
- State (
useState) is data that, when changed, re-renders the component. - Props pass data from a parent to a child component.
Rendering a list
function TodoList({ todos }) {
return (
<ul>
{todos.map(t => <li key={t.id}>{t.title}</li>)}
</ul>
);
}Fetching in React
import { useEffect, useState } from "react";
function Todos() {
const [todos, setTodos] = useState([]);
useEffect(() => {
fetch("/api/todos").then(r => r.json()).then(setTodos);
}, []);
return <ul>{todos.map(t => <li key={t.id}>{t.title}</li>)}</ul>;
}Front-end checklist
- Show loading and error states
- Validate forms
- Make it responsive and keyboard friendly
- Never store secrets in front-end code
Practice
Recreate your to-do list from the JavaScript course as a React app.