React Js W3 School
React Js W3 School
Learning by Examples
Our "Show React" tool makes it easy to demonstrate React. It shows both the code and the result.
Example:
import React from 'react';
function Hello(props) {
root.render(<Hello />);
Learning by Exercises
React Exercises
Exercise:
Enter the correct ReactDOM method to render the React element to the DOM.
Open your terminal in the directory you would like to create your application.
Note: 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.
cd 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:
You will learn more about the create-react-app in the React Get Started chapter.
HTML
CSS
JavaScript
You should also have some experience with the new JavaScript features introduced in ECMAScript
6 (ES6), you will learn about them in the React ES6 chapter.
CHAPTER # 1: React Introduction
What is React?
React, sometimes referred to as a frontend JavaScript framework, is a JavaScript library created by
Facebook.
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 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 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.
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-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() {
</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.
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.
The create-react-app will set up everything you need to run a React application.
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:
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 './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>
);
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:
root.render(myFirstElement);
Run Example »
Exercise:
Enter the correct ReactDOM method to render the React element to the DOM.
So what makes React so popular rather than just using vanilla HTML,
CSS, and JavaScript? For that, let's first look at the 2 main features
of React:
1. Declarative Views
2. Component Based Approach
Of course there is more to React than this, but we'll focus on these
two features here. Before moving on and learning more about these
features, we must clearly understand the browser DOM.
Now, any tree must have a root node, right? Here, the root node
is document. Are you wondering where this document node came
from? Well, it's part of the browser. Any HTML tag you write is
going to be a direct or indirect child of the root node document.
Component-Based Approach
Everything in React is a component. A web page is a collection of
components.
Same with components in React. Don't get confused with the code in
the below images, as we are using a mix of HTML and JavaScript.
Hang in there, we will come to that in a second.
Code for component named Card
The above image represents a component called Card (since the
function name is Card). As mentioned earlier, functions or
components can be reused any number of times. That is exactly what
we are doing in the below image. We are reusing
the Card component (<Card />) four times. Keep in mind that,
writing <Card /> is equivalent to <Card></Card>. (Stick to the former
notation, since it's more common).
Card Component reused multiple times
Congrats if you thought of this! The four <Card /> components are
written inside another component called Home (since the function
name is Home, <Home />). Congrats again if you thought of this!
Of course you can reuse the <Home /> component, which in turn is a
collection of many <Card /> components. That is, we can nest any
number of components inside other components.
Now comes a big question: if components are going to be nested like
we mentioned, what is the topmost component? It's the <App
/> component (provided by React). Any custom component that you
write is going to be a direct or indirect child of the App component
in React.
On a high level, the whole component structure looks like a tree with
the root node as App.
Also keep in mind that component names have their first letter
capitalized. This convention is used to distinguish between a React
component and a regular HTML tag.
If you carefully observe the above images, we are using a mix of both
JavaScript and HTML. This is known as JSX (Javscript XML).
This is just a nice way to write React.
Weird isn't it ? This
is JSX
In the above image, we are assigning HTML to a variable
named element, just like we assign values to variables in JavaScript.
Of course, you can now reuse this variable (element) anywhere in
your code like this:
Output of the above code
And that's it about components in React. Now let's move onto the
next feature.
Declarative Views in React
In React, we don't actually interact with the browser DOM. Yes, you
heard it right! We interact with the virtual DOM, which is an exact
copy of the browser DOM, but in memory.
Yeah! We are dealing with a new DOM, other than the browser
DOM. This means that any React component that we write is inserted
as a child to the virtual DOM.
When we update the browser DOM (when not using React), it takes
a significant amount of time to lay out the elements and repaint the
screen for the user to see changes. This involves a huge section of the
DOM tree being repainted.
But, when using React, updates happen in the virtual DOM first.
Then, the browser DOM and virtual DOM are diffed or compared to
see if there are any updates made to virtual DOM that must be
reflected or updated in the browser DOM.
If there are any, only then are updates made to the browser DOM to
match the virtual DOM. And these updates are only made at places
where updates are to be carried out. This means that the entire
browser DOM is not updated as previously mentioned. This
improves speed and efficiency.
Only part of the DOM is getting updated, instead of whole
Advantages of React
Now that you know the main features of React, let's understand the
advantages of using it.
Now let's see, how to set up React on your machine and create a brand
new project.
What is DOM?
The DOM (Document Object Model) represents the web page as a tree structure. Any piece of HTML
that we write is added as a node, to this tree. With JavaScript, we can access any of these nodes (HTML
elements) and update their styles, attributes, and so on.
DOM stands for “Document Object Model,” which represents your application UI
and whenever the changes are made in the application, this DOM gets updated and
the user is able to visualize the changes. DOM is an interface that allows scripts to
update the content, style, and structure of the document. Virtual DOM is a node tree
similar to Real DOM that lists elements, content, and attributes as objects and
properties. React render () method creates a node tree from the react components. Then
it updates the node tree in response to the mutations in the data model caused by various
actions done in the UI.
Let’s take a simple example of an array
Now we want to replace python with javascript. For that, we need to create a new array.
Instead of this, we can just traverse to languages[2] and update only the element. Instead
of redoing the whole thing, we just changed the element which we needed to update.
The same thing is done by Virtual DOM. Instead of updating all the node elements, it
just updates the changed elements. Virtual DOM does the same thing. Instead of
updating all the node elements, it just updates the changed elements. Virtual DOM does
the same thing. Virtual DOM does the same thing. Instead of updating all the node
elements, it just updates the changed elements.
ReactDOM. Render () will create a Virtual and real DOM tree of the first load. When
events like click, keypress, or API response occur, Virtual DOM tree elements are
notified for state or prop change; if that state or props are updated, then the node
elements are updated. When changes are done in UI, the changes are also done in Virtual
DOM. Instead of updating all the nodes, Virtual DOM updates only those components
in which changes are made.
Once Virtual DOM contains all the updated changes, it is then compared with the Real
DOM and the difference is calculated between them.
Once Virtual DOM contains all the updated changes it is then compared with the Real
DOM and the difference is calculated between them.
Once the difference is calculated the real DOM will update only the new components
that have actually changed. This is called Reconciliation. Virtual DOM is faster
and more effective than Real DOM as it just focuses on the updated components
instead of updating the entire DOM.
CHAPTER # 3: React ES6
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
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.
Example
Create an object called "mycar" based on the Car class:
class Car {
constructor(name) {
this.brand = name;
Try it Yourself »
Note: The constructor function is called automatically when the object is initialized.
Method in Classes
You can add your own methods in a class:
Example
Create a method named "present":
class Car {
constructor(name) {
this.brand = name;
present() {
}
const mycar = new Car("Ford");
mycar.present();
Try it Yourself »
As you can see in the example above, you call the method by referring to the object's method name
followed by parentheses (parameters would go inside the parentheses).
Class Inheritance
To create a class inheritance, use the extends keyword.
A class created with a class inheritance inherits all the methods from another class:
Example
Create a class named "Model" which will inherit the methods from the "Car" class:
class Car {
constructor(name) {
this.brand = name;
present() {
constructor(name, mod) {
super(name);
this.model = mod;
}
show() {
mycar.show();
Try it Yourself »
By calling the super () method in the constructor method, we call the parent's constructor method
and gets access to the parent's properties and methods.
To learn more about classes, check out our JavaScript Classes section.
Before:
hello = function() {
Try it Yourself »
Try it Yourself »
It gets shorter! If the function has only one statement, and the statement returns a value, you can
remove the brackets and the return keyword: like below
Try it Yourself »
Note: This works only if the function has only one statement.
Try it Yourself »
In fact, if you have only one parameter, you can skip the parentheses as well:
Try it Yourself »
In regular functions the this keyword represented the object that called the function, which could
be the window, the document, a button or whatever.
With arrow functions, the this keyword always represents the object that defined the arrow
function.
Both examples call a method twice, first when the page loads, and once again when the user clicks
a button.
The first example uses a regular function, and the second example uses an arrow function.
The result shows that the first example returns two different objects (window and button), and the
second example returns the Header object twice.
Example
With a regular function, this represents the object that called the function:
class Header {
constructor() {
this.color = "Red";
//Regular function:
changeColor = function() {
document.getElementById("demo").innerHTML += this;
window.addEventListener("load", myheader.changeColor);
document.getElementById("btn").addEventListener("click", myheader.changeColor);
Example
With an arrow function, this represents the Header object no matter who called the function:
class Header {
constructor() {
this.color = "Red";
//Arrow function:
changeColor = () => {
document.getElementById("demo").innerHTML += this;
window.addEventListener("load", myheader.changeColor);
document.getElementById("btn").addEventListener("click", myheader.changeColor);
Try it Yourself »
Remember these differences when you are working with functions. Sometimes the behavior of
regular functions is what you want, if not, use arrow functions.
Variables
Before ES6 there was only one way of defining your variables: with the var keyword. If you did
not define them, they would be assigned to the global object. Unless you were in strict mode, then
you would get an error if your variables were undefined.
Now, with ES6, there are three ways of defining your variables: var, let, and const.
var
var x = 5.6;
If you use var inside of a block, i.e. a for loop, the variable is still available outside of that block.
let
let x = 5.6;
let is the block scoped version of var, and is limited to the block (or expression) where it is defined.
If you use let inside of a block, i.e. a for loop, the variable is only available inside of that loop.
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
const
const x = 5.6;
const is a variable that once it has been created, its value can never change.
Exercise:
Create a variable that cannot be changed.
x = 5.6;
Submit Answer »
Array Methods
There are many JavaScript array methods.
The .map() method allows you to run a function on each item in the array, returning a new array as
the result.
Example
Generate a list of items from an array:
Run Example »
Submit Answer »
Destructuring
To illustrate destructuring, we'll make a sandwich. Do you take everything out of the refrigerator
to make your sandwich? No, you only take out the items you would like to use on your sandwich.
Destructuring is exactly the same. We may have an array or object that we are working with, but
we only need some of the items contained in these.
Destructing Arrays
Here is the old way of assigning array items to a variable:
Before:
const vehicles = ['mustang', 'f-150', 'expedition'];
// old way
With destructuring:
const vehicles = ['mustang', 'f-150', 'expedition'];
const [car, truck, suv] = vehicles;
When destructuring arrays, the order that variables are declared is important.
If we only want the car and suv we can simply leave out the truck but keep the comma:
Example
function calculate(a, b) {
const add = a + b;
const subtract = a - b;
const multiply = a * b;
const divide = a / b;
Try it Yourself »
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Destructuring Objects
Here is the old way of using an object inside a function:
Before:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
myVehicle(vehicleOne);
// old way
function myVehicle(vehicle) {
const message = 'My ' + vehicle.type + ' is a ' + vehicle.color + ' ' + vehicle.brand + ' ' +
vehicle.model + '.';
With destructuring:
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red'
}
myVehicle(vehicleOne);
const message = 'My ' + type + ' is a ' + color + ' ' + brand + ' ' + model + '.';
Try it Yourself »
Notice that the object properties do not have to be declared in a specific order.
We can even destructure deeply nested objects by referencing the nested object then using a colon
and curly braces to again destructure the items needed from the nested object:
Example
const vehicleOne = {
brand: 'Ford',
model: 'Mustang',
type: 'car',
year: 2021,
color: 'red',
registration: {
city: 'Houston',
state: 'Texas',
country: 'USA'
myVehicle(vehicleOne)
const message = 'My ' + model + ' is registered in ' + state + '.';
}
Try it Yourself »
const [ ] = vehicles;
Submit Answer »
Spread Operator
The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or
object into another array or object.
Example
const numbersOne = [1, 2, 3];
Try it Yourself »
Try it Yourself »
Example
Combine these two objects:
const myVehicle = {
brand: 'Ford',
model: 'Mustang',
color: 'red'
const updateMyVehicle = {
type: 'car',
year: 2021,
color: 'yellow'
Try it Yourself »
Notice the properties that did not match were combined, but the property that did match, color, was
overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow.
Test Yourself With Exercises
Exercise:
Use the spread operator to combine the following arrays.
Submit Answer »
Modules
JavaScript modules allow you to break up your code into separate files.
Export
You can export a function or variable from any file.
Let us create a file named person.js, and fill it with the things we want to export.
In-line individually:
person.js
const age = 40
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Default Exports
Let us create another file, named message.js, and use it for demonstrating default export.
Example
message.js
};
Import
You can import modules into a file in two ways, based on if they are named exports or default
exports.
Named exports must be destructured using curly braces. Default exports do not.
Try it Yourself »
Try it Yourself »
Ternary Operator
The ternary operator is a simplified conditional operator like if / else.
Before:
if (authenticated) {
renderApp();
} else {
renderLogin();
Try it Yourself »
With Ternary
authenticated ? renderApp() : renderLogin();
Try it Yourself »
Submit Answer »
React renders HTML to the web page by using a function called ReactDOM.render().
The purpose of the function is to display the specified HTML code inside the specified HTML
element.
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":
ReactDOM.render(<p>Hello</p>, document.getElementById('root'));
<body>
<div id="root"></div>
</body>
Run Example »
Note that the element id does not have to be called "root", but this is the standard convention.
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
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>
);
ReactDOM.render(myelement, document.getElementById('root'));
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>
ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));
Run Example »
React JSX
❮ PreviousNext ❯
What is JSX?
JSX stands for JavaScript XML.
Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM without
any createElement() and/or appendChild() methods.
You are not required to use JSX, but JSX makes it easier to write React applications.
Here are two examples. The first uses JSX and the second does not:
Example 1
JSX:
root.render(myElement);
Run Example »
Example 2
Without JSX:
root.render(myElement);
Run Example »
As you can see in the first example, JSX allows us to write HTML directly within the JavaScript
code.
JSX is an extension of the JavaScript language based on ES6, and is translated into regular
JavaScript at runtime.
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Expressions in JSX
With JSX you can write expressions inside curly braces { }.
The expression can be a React variable, or property, or any other valid JavaScript expression. JSX
will execute the expression and return the result:
Example
Execute the expression 5 + 5:
Run Example »
Example
Create a list with three list items:
const myElement = (
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Cherries</li>
</ul>
);
Run Example »
So if you like to write two paragraphs, you must put them inside a parent element, like
a div element.
Example
Wrap two paragraphs inside one DIV element:
const myElement = (
<div>
<p>I am a paragraph.</p>
</div>
);
Run Example »
JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.
Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily
adding extra nodes to the DOM.
Example
Wrap two paragraphs inside a fragment:
const myElement = (
<>
<p>I am a paragraph.</p>
</>
);
Run Example »
Example
Close empty elements with />
Run Example »
JSX will throw an error if the HTML is not properly closed.
JSX solved this by using className instead. When JSX is rendered, it translates className attributes
into class attributes.
Example
Use attribute className instead of class in JSX:
Run Example »
Conditions - if statements
React supports if statements, but not inside JSX.
To be able to use conditional statements in JSX, you should put the if statements outside of the
JSX, or you could use a ternary expression instead:
Option 1:
Write if statements outside of the JSX code:
Example
Write "Hello" if x is less than 10, otherwise "Goodbye":
const x = 5;
if (x < 10) {
text = "Hello";
Run Example »
Option 2:
Use ternary expressions instead:
Example
Write "Hello" if x is less than 10, otherwise "Goodbye":
const x = 5;
Run Example »
Note that in order to embed a JavaScript expression inside JSX, the JavaScript must be wrapped
with curly braces, {}.
Submit Answer »
React Components
Components are independent and reusable bits of code. They serve the same purpose as JavaScript
functions, but work in isolation and return HTML.
Components come in two types, Class components and Function components, in this tutorial we
will concentrate on Function components.
In older React code bases, you may find Class components primarily used. It is now suggested to
use Function components along with Hooks, which were added in React 16.8. There is an optional
section on Class components for your reference.
Class Component
A class component must include the extends React.Component statement. This statement creates an
inheritance to React.Component, and gives your component access to React.Component's
functions.
The component also requires a render() method, this method returns HTML.
Example
Create a Class component called Car
render() {
Function Component
Here is the same example as above, but created using a Function component instead.
A Function component also returns HTML, and behaves much the same way as a Class component,
but Function components can be written using much less code, are easier to understand, and will
be preferred in this tutorial.
Example
Create a Function component called Car
function Car() {
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Rendering a Component
Now your React application has a component called Car, which returns an <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example
Display the Car component in the "root" element:
root.render(<Car />);
Run Example »
Props
Components can be passed as props, which stands for properties.
Props are like function arguments, and you send them into the component as attributes.
Example
Use an attribute to pass a color to the Car component, and use it in the render() function:
function Car(props) {
Run Example »
Components in Components
We can refer to components inside other components:
Example
Use the Car component inside the Garage component:
function Car() {
function Garage() {
return (
<>
<Car />
</>
);
root.render(<Garage />);
Run Example »
Components in Files
React is all about re-using code, and it is recommended to split your components into separate files.
To do that, create a new file with a .js file extension and put the code inside it:
Example
This is the new file, we named it "Car.js":
function Car() {
To be able to use the Car component, you have to import the file in your application.
Example
Now we import the "Car.js" file in the application, and we can use the Car component as if it was
created here.
root.render(<Car />);
Run Example »
With the addition of Hooks, Function components are now almost equivalent to Class components.
The differences are so minor that you will probably never need to use a Class component in React.
Even though Function components are preferred, there are no current plans on removing Class
components from React.
This section will give you an overview of how to use Class components in React.
Feel free to skip this section, and use Function Components instead.
React Components
Components are independent and reusable bits of code. They serve the same purpose as JavaScript
functions, but work in isolation and return HTML via a render() function.
Components come in two types, Class components and Function components, in this chapter you
will learn about Class components.
The component has to include the extends React.Component statement, this statement creates an
inheritance to React.Component, and gives your component access to React.Component's
functions.
The component also requires a render() method, this method returns HTML.
Example
Create a Class component called Car
render() {
Now your React application has a component called Car, which returns a <h2> element.
To use this component in your application, use similar syntax as normal HTML: <Car />
Example
Display the Car component in the "root" element:
root.render(<Car />);
Run Example »
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Component Constructor
If there is a constructor() function in your component, this function will be called when the
component gets initiated.
The constructor function is also where you honor the inheritance of the parent component by
including the super() statement, which executes the parent component's constructor function, and
your component has access to all the functions of the parent component ( React.Component).
Example
Create a constructor function in the Car component, and add a color property:
constructor() {
super();
render() {
Example
class Car extends React.Component {
constructor() {
super();
render() {
}
}
Run Example »
Props
Another way of handling component properties is by using props.
Props are like function arguments, and you send them into the component as attributes.
Example
Use an attribute to pass a color to the Car component, and use it in the render() function:
render() {
root.render(<Car color="red"/>);
Run Example »
Example
class Car extends React.Component {
constructor(props) {
super(props);
render() {
root.render(<Car model="Mustang"/>);
Run Example »
Components in Components
We can refer to components inside other components:
Example
Use the Car component inside the Garage component:
render() {
render() {
return (
<div>
</div>
);
root.render(<Garage />);
Run Example »
Components in Files
React is all about re-using code, and it can be smart to insert some of your components in separate
files.
To do that, create a new file with a .js file extension and put the code inside it:
Note that the file must start by importing React (as before), and it has to end with the
statement export default Car;.
Example
This is the new file, we named it Car.js:
render() {
Example
Now we import the Car.js file in the application, and we can use the Car component as if it was
created here.
root.render(<Car />);
Run Example »
You might have noticed that we used state earlier in the component constructor section.
The state object is where you store property values that belongs to the component.
Example
Specify the state object in the constructor method:
constructor(props) {
super(props);
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
Example
Specify all the properties your component need:
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
Example:
Refer to the state object in the render() method:
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
</div>
);
Run Example »
When a value in the state object changes, the component will re-render, meaning that the output
will change according to the new value(s).
Example:
Add a button with an onClick event that will change the color property:
constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My {this.state.brand}</h1>
<p>
It is a {this.state.color}
{this.state.model}
from {this.state.year}.
</p>
<button
type="button"
onClick={this.changeColor}
>Change color</button>
</div>
);
Run Example »
Always use the setState() method to change the state object, it will ensure that the component knows
its been updated and calls the render() method (and all the other lifecycle methods).
Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate during its three
main phases.
React has four built-in methods that gets called, in this order, when mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
The render() method is required and will always be called, the others are optional and will be called
if you define them.
constructor
The constructor() method is called before anything else, when the component is initiated, and it is
the natural place to set up the initial state and other initial values.
The constructor() method is called with the props, as arguments, and you should always start by
calling the super(props) before anything else, this will initiate the parent's constructor method and
allows the component to inherit methods from its parent (React.Component).
Example:
The constructor method is called, by React, every time you make a component:
constructor(props) {
super(props);
render() {
return (
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
Run Example »
getDerivedStateFromProps
The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM.
This is the natural place to set the state object based on the initial props.
It takes state as an argument, and returns an object with changes to the state.
The example below starts with the favorite color being "red", but
the getDerivedStateFromProps() method updates the favorite color based on the favcol attribute:
Example:
The getDerivedStateFromProps method is called right before the render method:
constructor(props) {
super(props);
render() {
return (
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header favcol="yellow"/>);
Run Example »
render
The render() method is required, and is the method that actually outputs the HTML to the DOM.
Example:
A simple component with a simple render() method:
render() {
return (
);
root.render(<Header />);
Run Example »
componentDidMount
The componentDidMount() method is called after the component is rendered.
This is where you run statements that requires that the component is already placed in the DOM.
Example:
At first my favorite color is red, but give me a second, and it is yellow instead:
constructor(props) {
super(props);
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
render() {
return (
);
root.render(<Header />);
Run Example »
Updating
The next phase in the lifecycle is when a component is updated.
React has five built-in methods that gets called, in this order, when a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
The render() method is required and will always be called, the others are optional and will be called
if you define them.
getDerivedStateFromProps
Also at updates the getDerivedStateFromProps method is called. This is the first method that is called
when a component gets updated.
This is still the natural place to set the state object based on the initial props.
The example below has a button that changes the favorite color to blue, but since
the getDerivedStateFromProps() method is called, which updates the state with the color from the
favcol attribute, the favorite color is still rendered as yellow:
Example:
If the component gets updated, the getDerivedStateFromProps() method is called:
constructor(props) {
super(props);
changeColor = () => {
this.setState({favoritecolor: "blue"});
render() {
return (
<div>
</div>
);
Run Example »
shouldComponentUpdate
In the shouldComponentUpdate() method you can return a Boolean value that specifies whether React
should continue with the rendering or not.
The example below shows what happens when the shouldComponentUpdate() method returns false:
Example:
Stop the component from rendering at any update:
constructor(props) {
super(props);
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
render() {
return (
<div>
</div>
);
root.render(<Header />);
Run Example »
Example:
Same example as above, but this time the shouldComponentUpdate() method returns true instead:
constructor(props) {
super(props);
shouldComponentUpdate() {
return true;
changeColor = () => {
this.setState({favoritecolor: "blue"});
render() {
return (
<div>
</div>
);
root.render(<Header />);
Run Example »
render
The render() method is of course called when a component gets updated, it has to re-render the
HTML to the DOM, with the new changes.
The example below has a button that changes the favorite color to blue:
Example:
Click the button to make a change in the component's state:
constructor(props) {
super(props);
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
render() {
return (
<div>
</div>
);
root.render(<Header />);
Run Example »
getSnapshotBeforeUpdate
In the getSnapshotBeforeUpdate() method you have access to the props and state before the update,
meaning that even after the update, you can check what the values were before the update.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
When the component has been mounted, a timer changes the state, and after one second, the
favorite color becomes "yellow".
This action triggers the update phase, and since this component has
a getSnapshotBeforeUpdate() method, this method is executed, and writes a message to the empty
DIV1 element.
Then the componentDidUpdate() method is executed and writes a message in the empty DIV2
element:
Example:
Use the getSnapshotBeforeUpdate() method to find out what the state object looked like before the
update:
constructor(props) {
super(props);
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
componentDidUpdate() {
document.getElementById("div2").innerHTML =
render() {
return (
<div>
<div id="div2"></div>
</div>
);
root.render(<Header />);
Run Example »
componentDidUpdate
The componentDidUpdate method is called after the component is updated in the DOM.
The example below might seem complicated, but all it does is this:
When the component is mounting it is rendered with the favorite color "red".
When the component has been mounted, a timer changes the state, and the color becomes "yellow".
This action triggers the update phase, and since this component has a componentDidUpdate method,
this method is executed and writes a message in the empty DIV element:
Example:
The componentDidUpdate method is called after the update has been rendered in the DOM:
constructor(props) {
super(props);
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
componentDidUpdate() {
document.getElementById("mydiv").innerHTML =
render() {
return (
<div>
<div id="mydiv"></div>
</div>
);
root.render(<Header />);
Run Example »
Unmounting
The next phase in the lifecycle is when a component is removed from the DOM, or unmounting as
React likes to call it.
React has only one built-in method that gets called when a component is unmounted:
componentWillUnmount()
componentWillUnmount
The componentWillUnmount method is called when the component is about to be removed from the
DOM.
Example:
Click the button to delete the header:
constructor(props) {
super(props);
delHeader = () => {
this.setState({show: false});
render() {
let myheader;
if (this.state.show) {
};
return (
<div>
{myheader}
</div>
);
}
class Child extends React.Component {
componentWillUnmount() {
render() {
return (
<h1>Hello World!</h1>
);
root.render(<Container />);
Run Example »
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 (
<>
<h1>Who lives in my garage?</h1>
</>
);
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 (
<>
</>
);
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 (
<>
</>
);
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 />
</>
);
}
React has the same events as HTML: click, change, mouseover etc.
Adding Events
React events are written in camelCase syntax:
React:
<button onClick={shoot}>Take the Shot!</button>
HTML:
<button onclick="shoot()">Take the Shot!</button>
Example:
Put the shoot function inside the Football component:
function Football() {
alert("Great Shot!");
return (
);
root.render(<Football />);
Run Example »
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Passing Arguments
To pass an argument to an event handler, use an arrow function.
Example:
Send "Goal!" as a parameter to the shoot function, using arrow function:
function Football() {
alert(a);
return (
);
root.render(<Football />);
Run Example »
Example:
Arrow Function: Sending the event object manually:
function Football() {
alert(b.type);
/*
'b' represents the React event that triggered the function,
*/
return (
);
root.render(<Football />);
Run Example »
if Statement
We can use the if JavaScript operator to decide which component to render.
Example:
We'll use these two components:
function MissedGoal() {
return <h1>MISSED!</h1>;
function MadeGoal() {
return <h1>Goal!</h1>;
Example:
Now, we'll create another component that chooses which component to render based on a condition:
function Goal(props) {
if (isGoal) {
return <MadeGoal/>;
return <MissedGoal/>;
Run Example »
Example:
const root = ReactDOM.createRoot(document.getElementById('root'));
Run Example »
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Example:
We can embed JavaScript expressions in JSX by using curly braces:
function Garage(props) {
return (
<>
<h1>Garage</h1>
<h2>
</>
);
Run Example »
Example:
const cars = [];
Run Example »
Ternary Operator
Another way to conditionally render elements is by using a ternary operator.
Example:
Return the MadeGoal component if isGoal is true, otherwise return the MissedGoal component:
function Goal(props) {
const isGoal = props.isGoal;
return (
<>
</>
);
Run Example »
function App({isLoggedIn}) {
return (
<>
<h1>My Application</h1>
{isLoggedIn <Profile /> }
</>
);
}
React Lists
❮ PreviousNext ❯
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>
</ul>
</>
);
}
root.render(<Garage />);
Run Example »
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 for the list items.
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Keys
Keys allow React to keep track of elements. This way, if an item is updated or removed, only that
item will be re-rendered instead of the entire list.
Keys need to be unique to each sibling. But they can be duplicated globally.
Generally, the key should be a unique ID assigned to each item. As a last resort, you can use the
array index as a key.
Example:
Let's refactor our previous example to include keys:
function Car(props) {
function Garage() {
const cars = [
];
return (
<>
<ul>
</ul>
</>
);
root.render(<Garage />);
Run Example »
function GroceryList() {
const items = [
{id: 1, name: 'bread'},
{id: 2, name: 'milk'},
{id: 3, name: 'eggs'}
];
return (
<>
<h1>Grocery List</h1>
<ul>
{items.map((item) => <li ={item.id}>{item.name}</li>)}
</ul>
</>
);
}
Submit Answer »
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>Enter your name:
</label>
</form>
root.render(<MyForm />);
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:
return (
<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 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:
function MyForm() {
}
const handleSubmit = (event) => {
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>
}
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>
</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:
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>
<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.
React Router
❮ PreviousNext ❯
Create React App doesn't include page routing.
npm i -D react-router-dom
If you are upgrading from v5, you will need to use the @latest flag:
npm i -D react-router-dom@latest
Folder Structure
To create an application with multiple page routes, let's first start with the file structure.
Within the src folder, we'll create a folder named pages with several files:
src\pages\:
Layout.js
Home.js
Blogs.js
Contact.js
NoPage.js
Basic Usage
Now we will use our Router in our index.js file.
Example
Use React Router to route to pages based on URL:
index.js:
return (
<BrowserRouter>
<Routes>
</Route>
</Routes>
</BrowserRouter>
);
root.render(<App />);
Run Example »
Example Explained
We wrap our content first with <BrowserRouter>.
Then we define our <Routes>. An application can have multiple <Routes>. Our basic example only
uses one.
<Route>s can be nested. The first <Route> has a path of / and renders the Layout component.
The nested <Route>s inherit and add to the parent route. So the blogs path is combined with the
parent and becomes /blogs.
The Home component route does not have a path but has an index attribute. That specifies this route
as the default route for the parent route, which is /.
Setting the path to * will act as a catch-all for any undefined URLs. This is great for a 404 error
page.
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
Pages / Components
The Layout component has <Outlet> and <Link> elements.
<Link> is used to set the URL and keep track of browsing history.
Anytime we link to an internal path, we will use <Link> instead of <a href="">.
The "layout route" is a shared component that inserts common content on all pages, such as a
navigation menu.
Layout.js:
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/blogs">Blogs</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Outlet />
</>
};
Home.js:
return <h1>Home</h1>;
};
export default Home;
Blogs.js:
};
Contact.js:
};
NoPage.js:
return <h1>404</h1>;
};
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:
};
return (
<>
<hr />
<div>
Count: {count}
<button onClick={increment}>+</button>
</div>
</>
);
};
root.render(<App />);
Todos.js:
console.log("child render");
return (
<>
<h2>My Todos</h2>
{todos.map((todo, index) => {
})}
</>
);
};
Run Example »
Now the Todos component only re-renders when the todos that are passed to it through props are
updated.
❮ PreviousNext ❯
There are many ways to style React with CSS, this tutorial will take a closer look at three
common ways:
Inline styling
CSS stylesheets
CSS Modules
Inline Styling
To style an element with the inline style attribute, the value must be a JavaScript object:
Example:
Insert an object with the styling information:
return (
<>
</>
);
Run Example »
Note: In JSX, JavaScript expressions are written inside curly braces, and since JavaScript objects
also use curly braces, the styling in the example above is written inside two sets of curly braces {{}}.
Example:
Use backgroundColor instead of background-color:
return (
<>
</>
);
Run Example »
JavaScript Object
You can also create an object with styling information, and refer to it in the style attribute:
Example:
Create a style object named myStyle:
const myStyle = {
color: "white",
backgroundColor: "DodgerBlue",
padding: "10px",
fontFamily: "Sans-Serif"
};
return (
<>
</>
);
Run Example »
w3schoolsCERTIFIED.2022
Get Certified!
Complete the React modules, do the exercises, take the exam and become w3schools certified!!
$95 ENROLL
CSS Stylesheet
You can write your CSS styling in a separate file, just save the file with the .css file extension, and
import it in your application.
App.css:
Create a new file called "App.css" and insert some CSS code in it:
body {
background-color: #282c34;
color: white;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
Note: You can call the file whatever you like, just remember the correct file extension.
index.js:
import React from 'react';
import './App.css';
return (
<>
<h1>Hello Style!</h1>
);
root.render(<Header />);
Run Example »
CSS Modules
Another way of adding styles to your application is to use CSS Modules.
CSS Modules are convenient for components that are placed in separate files.
The CSS inside a module is available only for the component that imported it, and you do not have
to worry about name conflicts.
Create the CSS module with the .module.css extension, example: my-style.module.css.
Create a new file called "my-style.module.css" and insert some CSS code in it:
my-style.module.css:
.bigblue {
color: DodgerBlue;
padding: 40px;
font-family: Sans-Serif;
text-align: center;
Car.js:
import styles from './my-style.module.css';
const Car = () => {
index.js:
import ReactDOM from 'react-dom/client';
root.render(<Car />);
Run Example »
color = "purple"
What is Sass
Sass is a CSS pre-processor.
Sass files are executed on the server and sends CSS to the browser.
>npm i sass
In Sass files you can use variables and other Sass functions:
my-sass.scss:
Create a variable to define the color of the text:
$myColor: red;
h1 {
color: $myColor;
Import the Sass file the same way as you imported a CSS file:
index.js:
import React from 'react';
import './my-sass.scss';
return (
<>
<h1>Hello Style!</h1>
</>
);
root.render(<Header />);
Run Example »
CHAPTER # 10: React CSS Styling
React Hooks
❮ PreviousNext ❯
Hooks allow function components to have access to state and other React features. 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.
What is a Hook?
Hooks allow us to "hook" into React features such as state and lifecycle methods.
Example:
Here is an example of a Hook. Don't worry if it doesn't make sense. We will go into more detail in
the next section.
function FavoriteColor() {
return (
<>
<h1>My favorite color is {color}!</h1>
<button
type="button"
>Blue</button>
<button
type="button"
>Red</button>
<button
type="button"
>Pink</button>
<button
type="button"
>Green</button>
</>
);
root.render(<FavoriteColor />);
Run Example »
Here we are using the useState Hook to keep track of the application state.
Custom Hooks
If you have stateful logic that needs to be reused in several components, you can build your own
custom Hooks.