React is a JavaScript Library for Building User Interfaces
React is a JavaScript Library for Building User Interfaces
if Statement
Adding Events
We can use the if JavaScript operator to
React events are written in camelCase
decide which component to render.
syntax:
Example:
onClick instead of onclick.
We'll use these two components:
React event handlers are written inside
function MissedGoal() {
curly braces:
return <h1>MISSED!</h1>;
onClick={shoot} instead
}
of onclick="shoot()".
REACT NOTES
<h2>
function MadeGoal() { You have {cars.length} cars in your
return <h1>Goal!</h1>; garage.
} </h2>
Example: }
Now, we'll create another component that </>
chooses which component to render );
based on a condition: }
function Goal(props) {
const isGoal = props.isGoal; const cars = ['Ford', 'BMW', 'Audi'];
if (isGoal) { const root =
return <MadeGoal/>; ReactDOM.createRoot(document.getElem
} entById('root'));
return <MissedGoal/>; root.render(<Garage cars={cars} />);
}
If cars.length > 0 is equates to true, the
const root = expression after && will render.
ReactDOM.createRoot(document.getElem Try emptying the cars array:
entById('root')); Example:
root.render(<Goal isGoal={false} />); const cars = [];
const root =
Try changing the isGoal attribute to true: ReactDOM.createRoot(document.getElem
Example: entById('root'));
const root = root.render(<Garage cars={cars} />);
ReactDOM.createRoot(document.getElem
entById('root')); Ternary Operator
root.render(<Goal isGoal={true} />); Another way to conditionally render
elements is by using a ternary operator.
Logical && Operator condition ? true : false
Another way to conditionally render a We will go back to the goal example.
React component is by using Example:
the && operator. Return the MadeGoal component
Example: if isGoal is true, otherwise return
We can embed JavaScript expressions in the MissedGoal component:
JSX by using curly braces: function Goal(props) {
function Garage(props) { const isGoal = props.isGoal;
const cars = props.cars; return (
return ( <>
<> { isGoal ? <MadeGoal/> :
<h1>Garage</h1> <MissedGoal/> }
{cars.length > 0 && </>
REACT NOTES
); When you run this code in your create-
} react-app, it will work but you will receive
a warning that there is no "key" provided
const root = for the list items.
ReactDOM.createRoot(document.getElem
entById('root')); Keys
root.render(<Goal isGoal={false} />); Keys allow React to keep track of
elements. This way, if an item is updated
React Lists or removed, only that item will be re-
In React, you will render lists with some rendered instead of the entire list.
type of loop. Keys need to be unique to each sibling.
The JavaScript map() array method is But they can be duplicated globally.
generally the preferred method. Generally, the key should be a unique ID
If you need a refresher on assigned to each item. As a last resort, you
the map() method, check out the ES6 can use the array index as a key.
section. Example:
Let's refactor our previous example to
Example: include keys:
Let's render all of the cars from our function Car(props) {
garage: return <li>I am a { props.brand }</li>;
function Car(props) { }
return <li>I am a { props.brand }</li>;
} function Garage() {
const cars = [
function Garage() { {id: 1, brand: 'Ford'},
const cars = ['Ford', 'BMW', 'Audi']; {id: 2, brand: 'BMW'},
return ( {id: 3, brand: 'Audi'}
<> ];
<h1>Who lives in my garage?</h1> return (
<ul> <>
{cars.map((car) => <Car brand={car} <h1>Who lives in my garage?</h1>
/>)} <ul>
</ul> {cars.map((car) => <Car key={car.id}
</> brand={car.brand} />)}
); </ul>
} </>
);
const root = }
ReactDOM.createRoot(document.getElem
entById('root'));
root.render(<Garage />);
REACT NOTES
const root = In HTML, form data is usually handled by
ReactDOM.createRoot(document.getElem the DOM.
entById('root')); In React, form data is usually handled by
root.render(<Garage />); the components.
When the data is handled by the
React Forms components, all the data is stored in the
Just like in HTML, React uses forms to component state.
allow users to interact with the web page. You can control changes by adding event
handlers in the onChange attribute.
Adding Forms in React We can use the useState Hook to keep
You add a form with React like any other track of each inputs value and provide a
element: "single source of truth" for the entire
Example: application.
Add a form that allows users to enter their See the React Hooks section for more
name: information on Hooks.
function MyForm() { Example:
return ( Use the useState Hook to manage the
<form> input:
<label>Enter your name: import { useState } from 'react';
<input type="text" /> import ReactDOM from 'react-dom/client';
</label>
</form> function MyForm() {
) const [name, setName] = useState("");
}
const root = return (
ReactDOM.createRoot(document.getElem <form>
entById('root')); <label>Enter your name:
root.render(<MyForm />); <input
type="text"
This will work as normal, the form will value={name}
submit and the page will refresh. onChange={(e) =>
But this is generally not what we want to setName(e.target.value)}
happen in React. />
We want to prevent this default behavior </label>
and let React control the form. </form>
)
Handling Forms }
Handling forms is about how you handle
the data when it changes value or gets const root =
submitted. ReactDOM.createRoot(document.getElem
entById('root'));
REACT NOTES
root.render(<MyForm />); type="button"
onClick={() => setColor("pink")}
React Hooks >Pink</button>
Hooks were added to React in version <button
16.8. type="button"
Hooks allow function components to have onClick={() => setColor("green")}
access to state and other React features. >Green</button>
Because of this, class components are </>
generally no longer needed. );
Although Hooks generally replace class }
components, there are no plans to remove
classes from React. const root =
ReactDOM.createRoot(document.getElem
What is a Hook? entById('root'));
Hooks allow us to "hook" into React root.render(<FavoriteColor />);
features such as state and lifecycle Run Example »
methods. You must import Hooks from react.
Example: Here we are using the useState Hook to
Here is an example of a Hook. Don't worry keep track of the application state.
if it doesn't make sense. We will go into State generally refers to application data
more detail in the next section. or properties that need to be tracked.
import React, { useState } from "react";
import ReactDOM from "react- Hook Rules
dom/client"; There are 3 rules for hooks:
• Hooks can only be called inside
function FavoriteColor() { React function components.
const [color, setColor] = useState("red"); • Hooks can only be called at the top
level of a component.
return ( • Hooks cannot be conditional
<> Note: Hooks will not work in React class
<h1>My favorite color is {color}!</h1> components.
<button
type="button" React useState Hook
onClick={() => setColor("blue")} The React useState Hook allows us to track
>Blue</button> state in a function component.
<button State generally refers to data or properties
type="button" that need to be tracking in an application.
onClick={() => setColor("red")}
>Red</button>
<button
REACT NOTES
Import useState Read State
To use the useState Hook, we first need We can now include our state anywhere in
to import it into our component. our component.
Example: Example:
At the top of your Use the state variable in the rendered
component, import the useState Hook. component.
import { useState } from "react"; import { useState } from "react";
Notice that we are import ReactDOM from "react-
destructuring useState from react as it is a dom/client";
named export.
To learn more about destructuring, check function FavoriteColor() {
out the ES6 section. const [color, setColor] = useState("red");