What Is React
What Is React
What Is React
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).
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.
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!
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() {
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
The create-react-app will set up everything you need to run a React application.
cd my-react-app
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:
/myReactApp/src/App.js:
import './App.css';
function App() {
return (
<div className="App">
<header className="App-header">
<p>
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
export default App;
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.
function App() {
return (
<div className="App">
<h1>Hello World!</h1>
</div>
);
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:
Classes
ES6 introduced classes.
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.
Classes
Arrow Functions
Variables (let, const, var)
Array Methods like .map()
Destructuring
Modules
Ternary Operator
Spread Operator
const myFirstElement = <h1>Hello React!</h1>
root.render(myFirstElement);
Run Example »
The purpose of the function is to define the HTML element where a React
component should be displayed.
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":
root.render(<p>Hello</p>);
<body>
<div id="root"></div>
</body>
Run Example »
import React from 'react';
import ReactDOM from 'react-dom/client';
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>
);
root.render(myelement);
Run Example »
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>
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>
);
}
React Props
❮ PreviousNext ❯
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:
Example
Use the brand attribute in the component:
function Car(props) {
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) {
}
function Garage() {
return (
<>
</>
);
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) {
function Garage() {
return (
<>
</>
);
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) {
function Garage() {
return (
<>
</>
);
}
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.
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 } />
</>
);
}
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) {
function Garage() {
return (
<>
<ul>
</>
);
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>
</>
);
}
/*
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.
*/
React Forms
❮ PreviousNext ❯
Just like in HTML, React uses forms to allow users to interact with the web
page.
Example:
Add a form that allows users to enter their name:
function MyForm() {
return (
<form>
</label>
</form>
Run Example »
This will work as normal, the form will submit and the page will refresh.
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.
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.
Example:
Use the useState Hook to manage the input:
function MyForm() {
<form>
<input
type="text"
value={name}
/>
</label>
</form>
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:
function MyForm() {
event.preventDefault();
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={name}
/>
</label>
</form>
root.render(<MyForm />);
Run Example »
To update the state, use square brackets [bracket notation] around the
property name.
Example:
Write a form with two input fields:
function MyForm() {
event.preventDefault();
alert(inputs);
return (
<form onSubmit={handleSubmit}>
<input
type="text"
name="username"
value={inputs.username || ""}
onChange={handleChange}
/>
</label>
<input
type="number"
name="age"
value={inputs.age || ""}
onChange={handleChange}
/>
</label>
</form>
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>
</textarea>
function MyForm() {
);
setTextarea(event.target.value)
return (
<form>
</form>
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="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() {
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 »
function MyForm() {
return (
<form>
<label>Enter your name:
<input type="text" />
</label>
</form>
)
}
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>
)
}
function MyForm() {
const [name, setName] = useState("");
return (
<form onSubmit={handleSubmit}>
<label>Enter your name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<input type="submit" />
</form>
)
}
function MyForm() {
const [inputs, setInputs] = useState({});
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>
)
}
/*
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 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:
};
return (
<>
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
root.render(<App />);
Todos.js:
console.log("child render");
return (
<>
<h2>My Todos</h2>
</>
);
};
Run Example »
When you click the increment button, the Todos component re-renders.
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.
Example:
index.js:
import { useState } from "react";
};
return (
<>
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
Todos.js:
console.log("child render");
return (
<>
<h2>My Todos</h2>
})}
</>
);
};
Run Example »
Now the Todos component only re-renders when the todos that are passed to it
through props are updated.