0% found this document useful (0 votes)
3 views

React is a JavaScript Library for Building User Interfaces

The document provides an overview of React, a JavaScript library for building user interfaces, emphasizing its use of components, the virtual DOM, and ES6 features. It covers essential concepts such as classes, arrow functions, destructuring, and event handling, along with practical examples of creating components and managing props. Additionally, it explains conditional rendering and the use of JSX for rendering HTML in React applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

React is a JavaScript Library for Building User Interfaces

The document provides an overview of React, a JavaScript library for building user interfaces, emphasizing its use of components, the virtual DOM, and ES6 features. It covers essential concepts such as classes, arrow functions, destructuring, and event handling, along with practical examples of creating components and managing props. Additionally, it explains conditional rendering and the use of JSX for rendering HTML in React applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

REACT NOTES

React is a JavaScript library for building • Spread Operator


user interfaces.
React is used to build single-page
applications. Classes
React allows us to create reusable UI ES6 introduced classes.
components. A class is a type of function, but instead of
using the keyword function to initiate it,
What is React? we use the keyword class, and the
React, sometimes referred to as a properties are assigned inside
frontend JavaScript framework, is a a constructor() method.
JavaScript library created by Facebook. Example:
React is a tool for building UI components. A simple class constructor:
How does React Work? class Car {
React creates a VIRTUAL DOM in memory. constructor(name) {
Instead of manipulating the browser's this.brand = name;
DOM directly, React creates a virtual DOM }
in memory, where it does all the }
necessary manipulating, before making Notice the case of the class name. We
the changes in the browser DOM. have begun the name, "Car", with an
React only changes what needs to be uppercase character. This is a standard
changed! naming convention for classes.
Now you can create objects using the Car
React ES6 class:
What is ES6? Example:
ES6 stands for ECMAScript 6. Create an object called "mycar" based on
ECMAScript was created to standardize the Car class:
JavaScript, and ES6 is the 6th version of class Car {
ECMAScript, it was published in 2015, and constructor(name) {
is also known as ECMAScript 2015. this.brand = name;
}
}
Why Should I Learn ES6?
React uses ES6, and you should be familiar
const mycar = new Car("Ford");
with some of the new features like:
Note: The constructor function is called
• Classes
automatically when the object is
• Arrow Functions
initialized.
• Variables (let, const, var)
• Array Methods like .map()
• Destructuring
Class Inheritance
• Modules To create a class inheritance, use
• Ternary Operator the extends keyword.
REACT NOTES
A class created with a class inheritance hello = function() {
inherits all the methods from another return "Hello World!";
class: }
Example: Example:
Create a class named "Model" which will With Arrow Function:
inherit the methods from the "Car" class: hello = () => {
class Car { return "Hello World!";
constructor(name) { }
this.brand = name; It gets shorter! If the function has only
} one statement, and the statement returns
a value, you can remove the
present() { brackets and the return keyword:
return 'I have a ' + this.brand;
}
} What About this?
The handling of this is also different in
class Model extends Car {
arrow functions compared to regular
constructor(name, mod) {
functions.
super(name);
In short, with arrow functions there is no
this.model = mod;
binding of this.
}
In regular functions the this keyword
show() {
represented the object that called the
return this.present() + ', it is a ' +
function, which could be the window, the
this.model
document, a button or whatever.
}
With arrow functions,
}
the this keyword always represents the
const mycar = new Model("Ford",
object that defined the arrow function.
"Mustang");
Let us take a look at two examples to
mycar.show();
understand the difference.
The super() method refers to the parent
Both examples call a method twice, first
class.
when the page loads, and once again
By calling the super() method in the
when the user clicks a button.
constructor method, we call the parent's
The first example uses a regular function,
constructor method and get access to the
and the second example uses an arrow
parent's properties and methods.
function.
The result shows that the first example
Arrow Functions returns two different objects (window and
Arrow functions allow us to write shorter button), and the second example returns
function syntax: the Header object twice.
Example: Example:
Before:
REACT NOTES
With a regular function, this represents The .map() method allows you to run a
the object that called the function: function on each item in the array,
class Header { returning a new array as the result.
constructor() { In React, map() can be used to generate
this.color = "Red"; lists.
} Example:
Generate a list of items from an array:
//Regular function: const myArray = ['apple', 'banana',
changeColor = function() { 'orange'];

document.getElementById("demo").inner const myList = myArray.map((item) =>


HTML += this; <p>{item}</p>)
}
} Destructuring
Destructuring is exactly the same. We may
const myheader = new Header(); have an array or object that we are
working with, but we only need some of
//The window object calls the function: the items contained in these.
window.addEventListener("load", Destructuring makes it easy to extract only
myheader.changeColor); what is needed.

//A button object calls the function: Destructing Arrays


document.getElementById("btn").addEve Here is the old way of assigning array
ntListener("click", myheader.changeColor); items to a variable:
Example:
Variables Before:
Before ES6 there was only one way of const vehicles = ['mustang', 'f-150',
defining your variables: with 'expedition'];
the var keyword. If you did not define
them, they would be assigned to the // old way
global object. Unless you were in strict const car = vehicles[0];
mode, then you would get an error if your const truck = vehicles[1];
variables were undefined. const suv = vehicles[2];
Now, with ES6, there are three ways of Here is the new way of assigning array
defining your variables: var, let, and const. items to a variable:
Example
Array Methods With destructuring:
There are many JavaScript array methods. const vehicles = ['mustang', 'f-150',
One of the most useful in React is 'expedition'];
the .map() array method.
REACT NOTES
const [car, truck, suv] = vehicles; You can create named exports two ways.
When destructuring arrays, the order that In-line individually, or all at once at the
variables are declared is important. bottom.
If we only want the car and suv we can Import
simply leave out the truck but keep the You can import modules into a file in two
comma: ways, based on if they are named exports
const vehicles = ['mustang', 'f-150', or default exports.
'expedition']; Named exports must be destructured
using curly braces. Default exports do not.
const [car,, suv] = vehicles; Example:
Import named exports from the file
Spread Operator person.js:
The JavaScript spread operator (...) allows import { name, age } from "./person.js";
us to quickly copy all or part of an existing
array or object into another array or Ternary Operator
object. The ternary operator is a simplified
Example: conditional operator like if / else.
const numbersOne = [1, 2, 3]; Syntax: condition ? <expression if true> :
const numbersTwo = [4, 5, 6]; <expression if false>
const numbersCombined = Here is an example using if / else:
[...numbersOne, ...numbersTwo]; Example:
Before:
Modules if (authenticated) {
JavaScript modules allow you to break up renderApp();
your code into separate files. } else {
This makes it easier to maintain the code- renderLogin();
base. }
ES Modules rely on Here is the same example using a ternary
the import and export statements. operator:
Example:
Export With Ternary
You can export a function or variable from authenticated ? renderApp() :
any file. renderLogin();
Let us create a file named person.js, and
fill it with the things we want to export. React Render HTML
There are two types of exports: Named React's goal is in many ways to render
and Default. HTML in a web page.
React renders HTML to the web page by
Named Exports using a function called createRoot() and its
method render().
REACT NOTES
any createElement() and/or appendChild(
The createRoot Function ) methods.
The createRoot() function takes one JSX converts HTML tags into react
argument, an HTML element. elements.
The purpose of the function is to define You are not required to use JSX, but JSX
the HTML element where a React makes it easier to write React applications.
component should be displayed. Here are two examples. The first uses JSX
and the second does not:
The render Method Example1:
The render() method is then called to JSX:
define the React component that should const myElement = <h1>I Love JSX!</h1>;
be rendered.
But render where? const root =
There is another folder in the root ReactDOM.createRoot(document.getElem
directory of your React project, named entById('root'));
"public". In this folder, there is root.render(myElement);
an index.html file.
You'll notice a single <div> in the body of Example 2
this file. This is where our React Without JSX:
application will be rendered. const myElement =
Example: React.createElement('h1', {}, 'I do not use
Display a paragraph inside an element JSX!');
with the id of "root":
const container = const root =
document.getElementById('root'); ReactDOM.createRoot(document.getElem
const root = entById('root'));
ReactDOM.createRoot(container); root.render(myElement);
root.render(<p>Hello</p>);
React Components
React JSX Components are like functions that return
What is JSX? HTML elements.
JSX stands for JavaScript XML. Components come in two types, Class
JSX allows us to write HTML in React. components and Function components, in
JSX makes it easier to write and add HTML this tutorial we will concentrate on
in React. Function components.

Coding JSX Create Your First Component


JSX allows us to write HTML elements in When creating a React component, the
JavaScript and place them in the DOM component's name MUST start with an
without upper case letter.
REACT NOTES
Class Component In React, component properties should be
A class component must include kept in an object called state.
the extends React.Component statement. You will learn more about state later in
This statement creates an inheritance to this tutorial.
React.Component, and gives your The constructor function is also where you
component access to React.Component's honor the inheritance of the parent
functions. component by including
The component also requires the super() statement, which executes the
a render() method, this method returns parent component's constructor function,
HTML. and your component has access to all the
Example: functions of the parent component
Create a Class component called Car (React.Component).
class Car extends React.Component { Example:
render() { Create a constructor function in the Car
return <h2>Hi, I am a Car!</h2>; component, and add a color property:
} class Car extends React.Component {
} constructor() {
super();
Function Component this.state = {color: "red"};
Here is the same example as above, but }
created using a Function component render() {
instead. return <h2>I am a Car!</h2>;
A Function component also returns HTML, }
and behaves much the same way as a }
Class component, but Function
components can be written using much Use the color property in the render()
less code, are easier to understand, and function:
will be preferred in this tutorial. Example:
Example: class Car extends React.Component {
Create a Function component called Car constructor() {
function Car() { super();
return <h2>Hi, I am a Car!</h2>; this.state = {color: "red"};
} }
render() {
return <h2>I am a {this.state.color}
Component Constructor
Car!</h2>;
If there is a constructor() function in your
}
component, this function will be called
}
when the component gets initiated.
The constructor function is where you
initiate the component's properties.
REACT NOTES
React Props React:
Props are arguments passed into React <button onClick={shoot}>Take the
components. Shot!</button>
Props are passed to components via HTML HTML:
attributes. <button onclick="shoot()">Take the
props stands for properties. Shot!</button>

React Props Example:


React Props are like function arguments in Put the shoot function inside
JavaScript and attributes in HTML. the Football component:
To send props into a component, use the function Football() {
same syntax as HTML attributes: const shoot = () => {
Example: alert("Great Shot!");
Add a "brand" attribute to the Car }
element:
const myElement = <Car brand="Ford" />; return (
<button onClick={shoot}>Take the
The component receives the argument as shot!</button>
a props object: );
Example: }
Use the brand attribute in the component:
function Car(props) { const root =
return <h2>I am a { props.brand }!</h2>; ReactDOM.createRoot(document.getElem
} entById('root'));
root.render(<Football />);

React Conditional Rendering


React Events
Just like HTML DOM events, React can
In React, you can conditionally render
perform actions based on user events.
components.
React has the same events as HTML: click,
There are several ways to do this.
change, mouseover etc.

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");

Initialize useState return <h1>My favorite color is


We initialize our state by {color}!</h1>
calling useState in our function }
component.
useState accepts an initial state and const root =
returns two values: ReactDOM.createRoot(document.getElem
• The current state. entById('root'));
• A function that updates the state. root.render(<FavoriteColor />);
Example:
Initialize state at the top of the function React useEffect Hooks
component. The useEffect Hook allows you to perform
import { useState } from "react"; side effects in your components.
Some examples of side effects are:
function FavoriteColor() { fetching data, directly updating the DOM,
const [color, setColor] = useState(""); and timers.
} useEffect accepts two arguments. The
Notice that again, we are destructuring second argument is optional.
the returned values from useState. useEffect(<function>, <dependency>)
The first value, color, is our current state.
The second value, setColor, is the function Let's use a timer as an example.
that is used to update our state. Example:
These names are variables that can be Use setTimeout() to count 1 second after
named anything you would like. initial render:
Lastly, we set the initial state to an empty import { useState, useEffect } from "react";
string: useState("") import ReactDOM from "react-
dom/client";
REACT NOTES
function Timer() { the useState Hook, we would be caught in
const [count, setCount] = useState(0); an infinite loop since this Hook itself
causes a re-render.
useEffect(() => { To avoid this, we can use the useRef Hook.
setTimeout(() => { Example:
setCount((count) => count + 1); Use useRef to track application renders.
}, 1000); import { useState, useEffect, useRef } from
}); "react";
import ReactDOM from "react-
return <h1>I've rendered {count} dom/client";
times!</h1>;
} function App() {
const [inputValue, setInputValue] =
const root = useState("");
ReactDOM.createRoot(document.getElem const count = useRef(0);
entById('root'));
root.render(<Timer />); useEffect(() => {
count.current = count.current + 1;
React useContext Hook });
React Context
React Context is a way to manage state return (
globally. <>
It can be used together with <input
the useState Hook to share state between type="text"
deeply nested components more easily value={inputValue}
than with useState alone. onChange={(e) =>
setInputValue(e.target.value)}
/>
React useRef Hook
<h1>Render Count:
{count.current}</h1>
The useRef Hook allows you to persist
</>
values between renders.
);
It can be used to store a mutable value
}
that does not cause a re-render when
updated.
const root =
It can be used to access a DOM element
ReactDOM.createRoot(document.getElem
directly.
entById('root'));
root.render(<App />);
Does Not Cause Re-renders
If we tried to count how many times our
useRef() only returns one item. It returns
application renders using
an Object called current.
REACT NOTES
When we initialize useRef we set the React useMemo Hook
initial value: useRef(0).
The React useMemo Hook returns a
React useReducer Hook memoized value.
The useReducer Hook is similar to Think of memoization as caching a value
the useState Hook. so that it does not need to be
It allows for custom state logic. recalculated.
If you find yourself keeping track of The useMemo Hook only runs when one
multiple pieces of state that rely on of its dependencies update.
complex logic, useReducer may be useful. This can improve performance.
The useMemo and useCallback Hooks are
Syntax similar. The main difference is
The useReducer Hook accepts two that useMemo returns a memoized value
arguments. and useCallback returns a memoized
useReducer(<reducer>, <initialState>) function. You can learn more
The reducer function contains your about useCallback in the useCallback
custom state logic and the initialStatecan chapter.
be a simple value but generally will
contain an object.
The useReducer Hook returns the
current stateand a dispatchmethod.

React useCallback Hook


The React useCallback Hook returns a
memoized callback function.
Think of memoization as caching a value
so that it does not need to be
recalculated.
This allows us to isolate resource intensive
functions so that they will not
automatically run on every render.
The useCallback Hook only runs when one
of its dependencies update.
This can improve performance.
The useCallback and useMemo Hooks are
similar. The main difference is
that useMemo returns a
memoized value and useCallback returns a
memoized function. You can learn more
about useMemo in the useMemo chapter.

You might also like