Module 3
Module 3
React Fundamentals
Introduction
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.
Example
Create a Class component called Car
• 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()
{
return <h2>Hi, I am a Car!</h2>;
}
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
Example
Use an attribute to pass a color to the Car component, and use it in the render() function:
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;
}
Example
Use the Car component inside the Garage component:
function Car() {
return <h2>I am a Car!</h2>;
}
function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage />);
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() {
return <h2>Hi, I am a Car!</h2>;
}
• Each component in React has a lifecycle which you can monitor and
manipulate during its three main phases.
• 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 render() method is required and will always be called, the others are optional and
will be called if you define them.
getDerivedStateFromProps
• 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 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:
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
static getDerivedStateFromProps(props, state) {
return {favoritecolor: props.favcol };
}
changeColor = () => {
this.setState({favoritecolor: "blue"});
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header favcol="yellow" />);
shouldComponentUpdate
• 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:
import React from 'react';
import ReactDOM from 'react-dom/client';
• 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()
# Start installation
sudo yum install -y nodejs
2. Install React
You can install React using npm package manager by using the below command.
npm install -g create-react-app
Installing a Library
• To install a library in your project, navigate to your project directory in your
terminal
• Then run the installation command. Let's try this with react-native-webview:
let’s go over the folders one by one and the and understand the motivation behind them
and the type of files you would store in them:
Assets: This folder contains all the media assets, such as images, videos, json files, etc..
Containers: The name is pretty self-explanatory. It contains all the Stateful Components
For each component or container, you would create a subfolder and then name it with the
same name as the component and inside that create the js/jsx file for your component.
4. Context:
• This folder contains all your context files if you are working with the Context API.
• These files can be directly added to the context folder without wrapping in a
subfolder but you could also do that.
5. Hoc:
• Higher Order Components or HOCs are special type of Components which wrap your
conventional Components/Containers to add some features or functionality to the
Wrapped Components.
• HOCs are widely used for a variety of functionality and is something you definitely
want to get used to.
6. Store:
• In large applications where there is a lot of information to be stored and managed in
state, it is preferable to use global state or a store.
• This provides an efficient way of state management in your React App.
React State
• React components has a built-in state object.
• The state object is where you store property values that belongs to the component.
• When the state object changes, the component re-renders.
Example:
Specify the state object in the constructor method:
class Car extends React.Component {
constructor(props) {
super(props);
this.state = {brand: "Ford"};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
Specify all the properties your component need:
• 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:
class Car extends React.Component {
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>
);
}
Props
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}
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" />
</>
);
}
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 } />
</>
);
}
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 } />
</>
);
}
npm i -D react-router-dom
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
Blogs.js:
NoPage.js:
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 />);
• 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.
• 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() {
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 />);
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> const root =
<input type="submit" /> ReactDOM.createRoot(document.getElementById('root'));
</form> )} root.render(<MyForm />);
Textarea
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:
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"
);
return (
<form>
<textarea value={textarea} onChange={handleChange} />
</form>
)
}
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:
function MyForm() {
const [myCar, setMyCar] = useState("Volvo");
return (
<form>
<select value={myCar} onChange={handleChange}>
<option value="Ford">Ford</option>
<option value="Volvo">Volvo</option>
<option value="Fiat">Fiat</option>
</select>
</form>
)
}
React Events
• Just like HTML DOM events, React can perform actions based on user events.
• React has the same events as HTML: click, change, mouseover etc.
Adding Events
• React events are written in camelCase syntax:
onClick instead of onclick.
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() {
const shoot = () => {
alert("Great Shot!");
}
return (
<button onClick={shoot}>Take the shot!</button>
);
}
Example:
Send "Goal!" as a parameter to the shoot function, using arrow function:
function Football() {
const shoot = (a) => {
alert(a);
}
return (
<button onClick={() => shoot("Goal!")}>Take the shot!</button>
);
}
Example:
Arrow Function: Sending the event object manually:
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 />);
Animation In ReactJS
• The animation is a technique to make an interactive web application.
• To add animation in ReactJS an explicit group of components is used.
• These explicit group of components are also known as the React Transition Group, which
is technically an add-on component.
ReactTransitionGroup:
ReactCSSTransitionGroup:
Transition:
• To describe a transition from one component state to another over time, it has a
simple component API and is thus used to animate the mounting and unmounting of
a component.
• Entering, Entered, Exiting and Exited are the four states in which a user can access the
Transition component, thus this component is suitable for in-place transition states as
well.
CSSTransition:
• To write the transition and create animations, it uses CSS stylesheet classes.
• Inspired by the ng-animate library, it can be divided into three states, namely, Appear,
Enter and Exit.
• The CSSTransition component is also suitable to be used for inheriting all the props of
the transition component.
TransitionGroup: