What Is React

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

What is React?

React, sometimes referred to as a frontend JavaScript framework, is a


JavaScript library created by Facebook.

React is a tool for building UI components.

How does React Work?


React creates a VIRTUAL DOM in memory.

Instead of manipulating the browser's DOM directly, React creates a virtual


DOM in memory, where it does all the necessary manipulating, before making
the changes in the browser DOM.

React only changes what needs to be changed!

React finds out what changes have been made, and changes only what needs
to be changed.

You will learn the various aspects of how React does this in the rest of this
tutorial.

React.JS History
Current version of React.JS is V18.0.0 (April 2022).

Initial Release to the Public (V0.3.0) was in July 2013.

React.JS was first used in 2011 for Facebook's Newsfeed feature.

Facebook Software Engineer, Jordan Walke, created it.

Current version of create-react-app is v5.0.1 (April 2022).

create-react-app includes built tools such as webpack, Babel, and ESLint


React Getting Started
❮ PreviousNext ❯

To use React in production, you need npm which is included with Node.js.

To get an overview of what React is, you can write React code directly in
HTML.

But in order to use React in production, you need npm and Node.js installed.

React Directly in HTML


The quickest way start learning React is to write React directly in your HTML
files.

W3Schools Spaces
The easiest way to get started with creating HTML files is W3Schools Spaces!

It is the perfect place to create, edit, and share your work with others!

Get started for free ❯

Start by including three scripts, the first two let us write React code in our
JavaScripts, and the third, Babel, allows us to write JSX syntax and ES6 in older
browsers.

You will learn more about JSX in the React JSX chapter.

Example
Include three CDN's in your HTML file:

<!DOCTYPE html>

<html>
<head>

<script src="https://unpkg.com/react@18/umd/react.development.js"
crossorigin></script>

<script src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js" crossorigin></script>

<script
src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

</head>

<body>

<div id="mydiv"></div>

<script type="text/babel">

function Hello() {

return <h1>Hello World!</h1>;

const container = document.getElementById('mydiv');

const root = ReactDOM.createRoot(container);

root.render(<Hello />)

</script>

</body>

</html>

Try it Yourself »

This way of using React can be OK for testing purposes, but for production you
will need to set up a React environment.
w3schoolsCERTIFIED.2022

Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools
certified!!

$95 ENROLL

Setting up a React Environment


If you have npx and Node.js installed, you can create a React application by
using create-react-app.

If you've previously installed create-react-app globally, it is recommended that


you uninstall the package to ensure npx always uses the latest version
of create-react-app.

To uninstall, run this command: npm uninstall -g create-react-app.

Run this command to create a React application named my-react-app:

npx create-react-app my-react-app

The create-react-app will set up everything you need to run a React application.

Run the React Application


Now you are ready to run your first real React application!

Run this command to move to the my-react-app directory:

cd my-react-app

Run this command to run the React application my-react-app:


npm start

A new browser window will pop up with your newly created React App! If not,
open your browser and type localhost:3000 in the address bar.

The result:

Modify the React Application


So far so good, but how do I change the content?
Look in the my-react-app directory, and you will find a src folder. Inside
the src folder there is a file called App.js, open it and it will look like this:

/myReactApp/src/App.js:

import logo from './logo.svg';

import './App.css';

function App() {

return (

<div className="App">

<header className="App-header">

<img src={logo} className="App-logo" alt="logo" />

<p>

Edit <code>src/App.js</code> and save to reload.

</p>

<a

className="App-link"

href="https://reactjs.org"

target="_blank"

rel="noopener noreferrer"

>

Learn React

</a>

</header>

</div>

);

}
export default App;

Try changing the HTML content and save the file.

Notice that the changes are visible immediately after you save the file, you do
not have to reload the browser!

Example
Replace all the content inside the <div className="App"> with a <h1> element.

See the changes in the browser when you click Save.

function App() {

return (

<div className="App">

<h1>Hello World!</h1>

</div>

);

export default App;

Notice that we have removed the imports we do not need (logo.svg and
App.css).

The result:
What's Next?
Now you have a React Environment on your computer, and you are ready to
learn more about React.

In the rest of this tutorial we will use our "Show React" tool to explain the
various aspects of React, and how they are displayed in the browser.

If you want to follow the same steps on your computer, start by stripping down
the src folder to only contain one file: index.js. You should also remove any
unnecessary lines of code inside the index.js file to make them look like the
example in the "Show React" tool below:
Example
Click the "Run Example" button to see the result.

index.js:

import React from 'react';

import ReactDOM from 'react-dom/client';

React ES6 Classes


❮ PreviousNext ❯

Classes
ES6 introduced classes.

A class is a type of function, but instead of using the keyword function to


initiate it, we use the keyword class, and the properties are assigned inside
a constructor() method.

Example
A simple class constructor:

class Car {

constructor(name) {

this.brand = name;

Notice the case of the class name. We have begun the name, "Car", with an
uppercase character. This is a standard naming convention for classes.
Now you can create objects using the Car class:
What is ES6?
ES6 stands for ECMAScript 6.

ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of
ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

Why Should I Learn ES6?


React uses ES6, and you should be familiar with some of the new features like:

 Classes
 Arrow Functions
 Variables (let, const, var)
 Array Methods like .map()
 Destructuring
 Modules
 Ternary Operator
 Spread Operator
const myFirstElement = <h1>Hello React!</h1>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(myFirstElement);

Run Example »

Test Yourself With Exercises


Exercise:
Enter the correct ReactDOM method to render the React element to the DOM.

ReactDOM. (myElement, document.getElementById('root'));

React Render HTML


❮ PreviousNext ❯

React's goal is in many ways to render HTML in a web page.

React renders HTML to the web page by using a function


called createRoot() and its method render().

The creteRoot Function


The createRoot() function takes one argument, an HTML element.

The purpose of the function is to define the HTML element where a React
component should be displayed.

The render Method


The render() method is then called to define the React component that should be
rendered.

But render where?

There is another folder in the root directory of your React project, named
"public". In this folder, there is an index.html file.

You'll notice a single <div> in the body of this file. This is where our React
application will be rendered.

Example
Display a paragraph inside an element with the id of "root":

const container = document.getElementById('root');

const root = ReactDOM.createRoot(container);

root.render(<p>Hello</p>);

The result is displayed in the <div id="root"> element:

<body>

<div id="root"></div>

</body>

Run Example »
import React from 'react';
import ReactDOM from 'react-dom/client';

const container = document.getElementById('root');


const root = ReactDOM.createRoot(container);
root.render(<p>Hello</p>);
The HTML Code
The HTML code in this tutorial uses JSX which allows you to write HTML tags
inside the JavaScript code:

Do not worry if the syntax is unfamiliar, you will learn more about JSX in the
next chapter.

Example
Create a variable that contains HTML code and display it in the "root" node:

const myelement = (

<table>

<tr>

<th>Name</th>

</tr>

<tr>

<td>John</td>

</tr>

<tr>

<td>Elsa</td>

</tr>

</table>

);

const container = document.getElementById('root');

const root = ReactDOM.createRoot(container);

root.render(myelement);
Run Example »

The Root Node


The root node is the HTML element where you want to display the result.

It is like a container for content managed by React.

It does NOT have to be a <div> element and it does NOT have to have
the id='root':

Example
The root node can be called whatever you like:

<body>

<header id="sandy"></header>

</body>

Display the result in the <header id="sandy"> element:

const container = document.getElementById('sandy');

const root = ReactDOM.createRoot(container);

root.render(<p>Hallo</p>);

Run Example »
import React from 'react';
import ReactDOM from 'react-dom/client';

function Football() {
const shoot = (a, b) => {
alert(b.type);
/*
'b' represents the React event that triggered the function.
In this case, the 'click' event
*/
}

return (
<button onClick={(event) => shoot("Goal!", event)}>Take the shot!
</button>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Football />);

React Props
❮ PreviousNext ❯

Props are arguments passed into React components.

Props are passed to components via HTML attributes.

props stands for properties.

React Props
React Props are like function arguments in JavaScript and attributes in HTML.

To send props into a component, use the same syntax as HTML attributes:

Example
Add a "brand" attribute to the Car element:

const myElement = <Car brand="Ford" />;


The component receives the argument as a props object:

Example
Use the brand attribute in the component:

function Car(props) {

return <h2>I am a { props.brand }!</h2>;

Run Example »

w3schoolsCERTIFIED.2022

Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools
certified!!

$95 ENROLL

Pass Data
Props are also how you pass data from one component to another, as
parameters.

Example
Send the "brand" property from the Garage component to the Car component:

function Car(props) {

return <h2>I am a { props.brand }!</h2>;

}
function Garage() {

return (

<>

<h1>Who lives in my garage?</h1>

<Car brand="Ford" />

</>

);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

Run Example »

If you have a variable to send, and not a string as in the example above, you
just put the variable name inside curly brackets:

Example
Create a variable named carName and send it to the Car component:

function Car(props) {

return <h2>I am a { props.brand }!</h2>;

function Garage() {

const carName = "Ford";

return (

<>

<h1>Who lives in my garage?</h1>


<Car brand={ carName } />

</>

);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

Run Example »

Or if it was an object:

Example
Create an object named carInfo and send it to the Car component:

function Car(props) {

return <h2>I am a { props.brand.model }!</h2>;

function Garage() {

const carInfo = { name: "Ford", model: "Mustang" };

return (

<>

<h1>Who lives in my garage?</h1>

<Car brand={ carInfo } />

</>

);

}
const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

Run Example »
Note: React Props are read-only! You will get an error if you try to change their
value.

Test Yourself With Exercises


Exercise:
Create a variable named name and pass it to the Person component.

function Person(props) {
return <h2>I'm { props.name }!</h2>;
}

function Greeting() {
const name = "Jesse"
return (
<>
<h1>Hello!</h1>
<Person name= name />
</>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Greeting />);
import React from 'react';
import ReactDOM from 'react-dom/client';

function Car(props) {
return <h2>I am a { props.brand.model }!</h2>;
}

function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Garage />);

In React, you will render lists with some type of loop.

The JavaScript map() array method is generally the preferred method.

If you need a refresher on the map() method, check out the ES6 section.

Example:
Let's render all of the cars from our garage:

function Car(props) {

return <li>I am a { props.brand }</li>;

function Garage() {

const cars = ['Ford', 'BMW', 'Audi'];

return (

<>

<h1>Who lives in my garage?</h1>

<ul>

{cars.map((car) => <Car brand={car} />)}


</ul>

</>

);

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Garage />);

Run Example »
import React from 'react';
import ReactDOM from 'react-dom/client';

function Car(props) {
return <li>I am a { props.brand }</li>;
}

function Garage() {
const cars = ['Ford', 'BMW', 'Audi'];
return (
<>
<h1>Who lives in my garage?</h1>
<ul>
{cars.map((car) => <Car brand={car} />)}
</ul>
</>
);
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<Garage />);

/*
If you run this example in your create-react-app,
you will receive a warning that there is no "key" provided for the list
items.
*/

Who lives in my garage?


 I am a Ford
 I am a BMW
 I am a Audi

React Forms
❮ PreviousNext ❯

Just like in HTML, React uses forms to allow users to interact with the web
page.

Adding Forms in React


You add a form with React like any other element:

Example:
Add a form that allows users to enter their name:

function MyForm() {

return (

<form>

<label>Enter your name:

<input type="text" />

</label>

</form>

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<MyForm />);

Run Example »

This will work as normal, the form will submit and the page will refresh.

But this is generally not what we want to happen in React.

We want to prevent this default behavior and let React control the form.

Handling Forms
Handling forms is about how you handle the data when it changes value or gets
submitted.

In HTML, form data is usually handled by the DOM.

In React, form data is usually handled by the components.

When the data is handled by the components, all the data is stored in the
component state.

You can control changes by adding event handlers in the onChange attribute.

We can use the useState Hook to keep track of each inputs value and provide a
"single source of truth" for the entire application.

See the React Hooks section for more information on Hooks.

Example:
Use the useState Hook to manage the input:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [name, setName] = useState("");


return (

<form>

<label>Enter your name:

<input

type="text"

value={name}

onChange={(e) => setName(e.target.value)}

/>

</label>

</form>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<MyForm />);

Run Example »

w3schoolsCERTIFIED.2022

Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools
certified!!

$95 ENROLL
Submitting Forms
You can control the submit action by adding an event handler in
the onSubmit attribute for the <form>:

Example:
Add a submit button and an event handler in the onSubmit attribute:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [name, setName] = useState("");

const handleSubmit = (event) => {

event.preventDefault();

alert(`The name you entered was: ${name}`)

return (

<form onSubmit={handleSubmit}>

<label>Enter your name:

<input

type="text"

value={name}

onChange={(e) => setName(e.target.value)}

/>
</label>

<input type="submit" />

</form>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<MyForm />);

Run Example »

Multiple Input Fields


You can control the values of more than one input field by adding
a name attribute to each element.

We will initialize our state with an empty object.

To access the fields in the event handler use


the event.target.name and event.target.value syntax.

To update the state, use square brackets [bracket notation] around the
property name.

Example:
Write a form with two input fields:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [inputs, setInputs] = useState({});


const handleChange = (event) => {

const name = event.target.name;

const value = event.target.value;

setInputs(values => ({...values, [name]: value}))

const handleSubmit = (event) => {

event.preventDefault();

alert(inputs);

return (

<form onSubmit={handleSubmit}>

<label>Enter your name:

<input

type="text"

name="username"

value={inputs.username || ""}

onChange={handleChange}

/>

</label>

<label>Enter your age:

<input

type="number"
name="age"

value={inputs.age || ""}

onChange={handleChange}

/>

</label>

<input type="submit" />

</form>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<MyForm />);

Run Example »
Note: We use the same event handler function for both input fields, we could
write one event handler for each, but this gives us much cleaner code and is the
preferred way in React.

Textarea
The textarea element in React is slightly different from ordinary HTML.

In HTML the value of a textarea was the text between the start
tag <textarea> and the end tag </textarea>.

<textarea>

Content of the textarea.

</textarea>

In React the value of a textarea is placed in a value attribute. We'll use


the useState Hook to mange the value of the textarea:
Example:
A simple textarea with some content:

import { useState } from 'react';

import ReactDOM from 'react-dom/client';

function MyForm() {

const [textarea, setTextarea] = useState(

"The content of a textarea goes in the value attribute"

);

const handleChange = (event) => {

setTextarea(event.target.value)

return (

<form>

<textarea value={textarea} onChange={handleChange} />

</form>

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<MyForm />);

Run Example »
Select
A drop down list, or a select box, in React is also a bit different from HTML.

in HTML, the selected value in the drop down list was defined with
the selected attribute:

HTML:
<select>

<option value="Ford">Ford</option>

<option value="Volvo" selected>Volvo</option>

<option value="Fiat">Fiat</option>

</select>

In React, the selected value is defined with a value attribute on the select tag:

Example:
A simple select box, where the selected value "Volvo" is initialized in the
constructor:

function MyForm() {

const [myCar, setMyCar] = useState("Volvo");

const handleChange = (event) => {

setMyCar(event.target.value)

return (

<form>
<select value={myCar} onChange={handleChange}>

<option value="Ford">Ford</option>

<option value="Volvo">Volvo</option>

<option value="Fiat">Fiat</option>

</select>

</form>

Run Example »

By making these slight changes to <textarea> and <select>, React is able to


handle all input elements in the same way.

import React from 'react';


import ReactDOM from 'react-dom/client';

function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<MyForm />);

import { useState } from "react";


import ReactDOM from 'react-dom/client';

function MyForm() {
const [name, setName] = useState("");

return (
<form>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
</form>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<MyForm />);

import { useState } from "react";


import ReactDOM from 'react-dom/client';

function MyForm() {
const [name, setName] = useState("");

const handleSubmit = (event) => {


event.preventDefault();
alert(`The name you entered was: ${name}`);
}

return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<MyForm />);
mport { useState } from "react";
import ReactDOM from "react-dom/client";

function MyForm() {
const [inputs, setInputs] = useState({});

const handleChange = (event) => {


const name = event.target.name;
const value = event.target.value;
setInputs(values => ({...values, [name]: value}))
}

const handleSubmit = (event) => {


event.preventDefault();
console.log(inputs);
}

return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<label>Enter your age:
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
<input type="submit" />
</form>
)
}

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<MyForm />);

/*
Click F12 and navigate to the "Console view"
to see the result when you submit the form
React Memo
❮ PreviousNext ❯

Using memo will cause React to skip rendering a component if its props have
not changed.

This can improve performance.

This section uses React Hooks. See the React Hooks section for more
information on Hooks.

Problem
In this example, the Todos component re-renders even when the todos have not
changed.

Example:
index.js:

import { useState } from "react";

import ReactDOM from "react-dom/client";

import Todos from "./Todos";

const App = () => {

const [count, setCount] = useState(0);

const [todos, setTodos] = useState(["todo 1", "todo 2"]);

const increment = () => {


setCount((c) => c + 1);

};

return (

<>

<Todos todos={todos} />

<hr />

<div>

Count: {count}

<button onClick={increment}>+</button>

</div>

</>

);

};

const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<App />);

Todos.js:

const Todos = ({ todos }) => {

console.log("child render");

return (

<>

<h2>My Todos</h2>

{todos.map((todo, index) => {

return <p key={index}>{todo}</p>;


})}

</>

);

};

export default Todos;

Run Example »

When you click the increment button, the Todos component re-renders.

If this component was complex, it could cause performance issues.

w3schoolsCERTIFIED.2022

Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools
certified!!

$95 ENROLL

Solution
To fix this, we can use memo.

Use memoto keep the Todos component from needlessly re-rendering.

Wrap the Todos component export in memo:

Example:
index.js:
import { useState } from "react";

import ReactDOM from "react-dom/client";

import Todos from "./Todos";

const App = () => {

const [count, setCount] = useState(0);

const [todos, setTodos] = useState(["todo 1", "todo 2"]);

const increment = () => {

setCount((c) => c + 1);

};

return (

<>

<Todos todos={todos} />

<hr />

<div>

Count: {count}

<button onClick={increment}>+</button>

</div>

</>

);

};

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(<App />);

Todos.js:

import { memo } from "react";

const Todos = ({ todos }) => {

console.log("child render");

return (

<>

<h2>My Todos</h2>

{todos.map((todo, index) => {

return <p key={index}>{todo}</p>;

})}

</>

);

};

export default memo(Todos);

Run Example »

Now the Todos component only re-renders when the todos that are passed to it
through props are updated.

❮ Previous Log in to track progress Next ❯

You might also like