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

Module 3

Uploaded by

snehalparab183
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Module 3

Uploaded by

snehalparab183
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 73

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.

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.
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 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
• Function components
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

class Car extends React.Component


{
render()
{
return <h2>Hi, I am a Car!</h2>;
}
}
Function Component

• 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

Display the Car component in the "root" element:

import React from 'react';


import ReactDOM from 'react-dom/client';
function Car()
{
return <h2>Hi, I am a Car!</h2>;
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car />);
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:

import React from 'react';


import ReactDOM from 'react-dom/client';

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

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


root.render(<Car color="red"/>);
Components in Components
• We can refer to components inside other components:

Example
Use the Car component inside the Garage component:

import React from 'react';


import ReactDOM from 'react-dom/client';

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:

Note that the filename must start with an uppercase character.

Example
This is the new file, we named it "Car.js":

function Car() {
return <h2>Hi, I am a Car!</h2>;
}

export default Car;


Example
Now we import the "Car.js" file in the application, and we can use the Car component as if
it was created here.

import React from 'react';


import ReactDOM from 'react-dom/client';
import Car from './Car.js';

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


root.render(<Car />);
Lifecycle of Components

• Each component in React has a lifecycle which you can monitor and
manipulate during its three main phases.

The three phases are:


• Mounting
• Updating
• Unmounting.
Mounting

• Mounting means putting elements into the DOM.


• 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


• 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).

import React from 'react';


import ReactDOM from 'react-dom/client';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
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:

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 };
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header favcol="yellow"/>);
render
• The render() method is required, and is the method that actually outputs the HTML to
the DOM.

import React from 'react';


import ReactDOM from 'react-dom/client';

class Header extends React.Component {


render() {
return (
<h1>This is the content of the Header component</h1>
);
}
}

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


root.render(<Header />);
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.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
render() {
return (
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
Updating
• The next phase in the lifecycle is when a component is updated.
• A component is updated whenever there is a change in the component's state or props.
• 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

• 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

• In the shouldComponentUpdate() method you can return a Boolean value that


specifies whether React should continue with the rendering or not.

• The default value is true.

• The example below shows what happens when


the shouldComponentUpdate() method returns false:
import React from 'react';
import ReactDOM from 'react-dom/client';

class Header extends React.Component {


constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
shouldComponentUpdate() {
return false;
}
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 />);
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:
import React from 'react';
import ReactDOM from 'react-dom/client';

class Header extends React.Component {


constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
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 />);
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.

• If the getSnapshotBeforeUpdate() method is present, you should also include


the componentDidUpdate() method, otherwise you will get an error.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
getSnapshotBeforeUpdate(prevProps, prevState) {
document.getElementById("div1").innerHTML =
"Before the update, the favorite was " + prevState.favoritecolor;
}
componentDidUpdate() {
document.getElementById("div2").innerHTML =
"The updated favorite is " + this.state.favoritecolor;
}
render() {
return (
<div>
<h1>My Favorite Color is {this.state.favoritecolor}</h1>
<div id="div1"></div>
<div id="div2"></div>
</div>
);
}}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Header />);
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()

The componentWillUnmount method is called when the component is about to be


removed from the DOM.
import React from 'react';
import ReactDOM from 'react-dom/client';
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header</button>
</div>
); }}
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
); }
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Container />);
React Installation
There are two ways to install the ReactJS

1. Using NPM command

2. Using Create-react-app Command


Using NPM command
Pre-requisite for ReactJS
• NodeJS and NPM
• React and React DOM
• Webpack
• Babel

1 - Update Yum Repositories

# Install APT update


sudo yum -y update

2 - Install Node & NPM

# Start installation
sudo yum install -y nodejs

3 - Create React App

npx create-react-app myfirstreactapp


Using the create-react-app command
1. Install NodeJS and NPM
NodeJS and NPM are the platforms need to develop any ReactJS application.

2. Install React
You can install React using npm package manager by using the below command.
npm install -g create-react-app

3. Create a new React project


After the installation of React, you can create a new react project using create-react-
app command
create-react-app jtp-reactapp
npx create-react-app jtp-reactapp
The above command will install the react and create a new project with the name
jtp-reactapp.

4. Running the Server


After completing the installation process, you can start the server by running the
following command.
cd jtp-reactapp
npm start
Installing libraries
Finding Libraries
• React Native Directory is a searchable database of libraries built specifically for
React Native.
• This is the first place to look for a library for your React Native 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:

npm install react-native-webview


Folder and file structure
If you are just getting started with React, you are probably using create-react-app as your
toolchain. Create react App gives you the following folder structure.
The most common src folder looks somewhat like this:

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..

Components: This folder contains all the Presentational/Stateless Components

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.

Creating the state Object


The state object is initialized in the constructor:

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:

class Car extends React.Component {


constructor(props) {
super(props);
this.state = {
brand: "Ford",
model: "Mustang",
color: "red",
year: 1964
};
}
render() {
return (
<div>
<h1>My Car</h1>
</div>
);
}
}
Using the state Object
Refer to the state object anywhere in the component by using the this.state.propertyname syntax:
Example:
Refer to the state object in the render() method:
class Car extends React.Component {
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>
);
}
}
Changing the state Object
• To change a value in the state object, use the this.setState() method.

• 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

• Props are arguments passed into React components.


• Props are passed to components via HTML attributes.
• 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>;
}
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 />);
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 />);
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 />);
React Router
• Reate React App doesn't include page routing.
• React Router is the most popular solution.

Add React Router


To add React Router in your application, run this in the terminal from the root
directory of the application:

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

Each file will contain a very basic React component.


Basic Usage
Now we will use our Router in our index.js file.
import ReactDOM from "react-dom/client";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Layout from "./pages/Layout";
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {


return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="blogs" element={<Blogs />} />
<Route path="contact" element={<Contact />} />
<Route path="*" element={<NoPage />} />
</Route>
</Routes>
</BrowserRouter>
);}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
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.
Pages / Components

• The Layout component has <Outlet> and <Link> elements.


• The <Outlet> renders the current route selected.
• <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:

import { Outlet, Link } from "react-router-dom";


const Layout = () => {
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 />
</>
)
};
export default Layout;
Home.js:

const Home = () => {


return <h1>Home</h1>;
};

export default Home;

Blogs.js:

const Blogs = () => {


return <h1>Blog Articles</h1>;
};

export default Blogs;


Contact.js:

const Contact = () => {


return <h1>Contact Me</h1>;
};

export default Contact;

NoPage.js:

const NoPage = () => {


return <h1>404</h1>;
};

export default NoPage;


React Forms
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 />);

• 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.
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 />);
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

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:
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 />);
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:
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>
)
}
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 event handlers are written inside curly braces:


onClick={shoot} instead of onClick="shoot()".

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

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


root.render(<Football />);
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() {
const shoot = (a) => {
alert(a);
}

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

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


root.render(<Football />);
React Event Object
• Event handlers have access to the React event that triggered the function.
• In our example the event is the "click" event.

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.

Uses of React Transition Group:


• Managing component states.
• Defining entering and exciting transitions.
• Exposing transition states.
• Managing classes and group elements,
• Manipulating the DOM in useful ways.
• Makes easier implementation of visual transitions.
React Transition group APIs to create transitions:

ReactTransitionGroup:

Low-level API for animation.

ReactCSSTransitionGroup:

High-level API for implementing basic CSS transitions and animations.

Installation of React Transition group:

Command: $npm install react-transition-group --save


React Transition Group Components:
There are three main components of React Transition Group.

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:

• To manage a set of transition components in a list, the TransitionGroup component


is used.
• Being a state machine, it can control the mounting and unmounting of components
over time.
• The “TransitionGroup” component can have different animation within a
component, since it animates the list item on the basis of individual transition
component, along with the fact that it does not define any animation directly.
Example: render() {
App.js: const items = this.state.items.map((item, i) =>
(
import React, { Component } from 'react'; <div key={item} onClick={() =>
import { CSSTransitionGroup } from 'react- this.handleRemove(i)}>
transition-group'; {item}
class App extends React.Component { </div>
constructor(props) { ));
super(props); return (
this.state = {items: ['Happy', 'Joy', 'Smiling', <div>
'Juvenile']}; <h1>Wait for the Magic!!</h1>
this.handleAdd = this.handleAdd.bind(this); <button
} onClick={this.handleAdd}>Insert</button>
handleAdd() { <CSSTransitionGroup
const newItems = this.state.items.concat([ transitionName="magic"
prompt('Enter Name') transitionEnterTimeout={600}
]); transitionLeaveTimeout={500}>
this.setState({items: newItems}); {items}
} </CSSTransitionGroup>
handleRemove(i) { </div>
let newItems = this.state.items.slice(); );
newItems.splice(i, 1); }
this.setState({items: newItems}); }
} export default App;
Style.css:
Main.js:
.magic-enter {
import React from 'react'; opacity: 0.02;
import ReactDOM from 'react- }
dom'; .magic-enter.example-enter-active {
import App from './App.js'; opacity: 2;
ReactDOM.render(<App />, transition: opacity 550ms ease-in;
document.getElementById('app')); }
.magic-leave {
opacity: 2;
}
.magic-leave.example-leave-active {
opacity: 0.02;
transition: opacity 250ms ease-in;
}

You might also like