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

08. ReactJS

This document provides a comprehensive guide on getting started with ReactJS, covering its overview, environment setup, JSX, components, hooks, and component lifecycle. It explains key features such as one-way data binding, virtual DOM, and the use of hooks like useState and useEffect. The document also includes examples and best practices for building reusable UI components and managing state in React applications.

Uploaded by

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

08. ReactJS

This document provides a comprehensive guide on getting started with ReactJS, covering its overview, environment setup, JSX, components, hooks, and component lifecycle. It explains key features such as one-way data binding, virtual DOM, and the use of hooks like useState and useEffect. The document also includes examples and best practices for building reusable UI components and managing state in React applications.

Uploaded by

chhungsim.chuo
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Getting Started With

ReactJS
Prepared by Web
team
I. ReactJS Overview
II. Environment Setup
III.JSX & Components
Content IV.List & Key
V. React Hooks
VI.Component Life Cycle
VII.State & Props
Overview
Overview
⎊ Introduction
- ReactJS is a JavaScript library used for building
reusable UI components.
- It is a language for user interfaces, can be
compared to Angular & Vue.
- It is used at the client side and can be integrated
with other CSS frameworks like TailwindCSS.
Overview
⎊ Features
- JSX : It is a JavaScript syntax extension. It isn’t
necessary to use JSX in React development, but it
is recommended.
- Components : React is all about components.
Those components are all rendered in the client
side.
Overview
⎊ Features (cont.)
- One-way Data Binding : The data in react flows
only in one direction which means that the
properties (props) in the child component cannot
return the data to its parent component.
- Performance : react uses virtual DOM and
updates only the modified parts.
Overview
⎊ Features (cont.)
- Simplicity : ReactJS is a component-based which
makes the code reusable and it uses JSX which is a
combination of HTML and JavaScript. This makes
code easy to understand and debug.
Overview
⎊ Advantages of ReactJS
- It can be used on client and server side as well as
with other frameworks.
- Components and data patterns improve readability,
which helps to maintain larger apps.
Overview
⎊ Advantages of ReactJS
- React utilizes a virtual DOM, which is an in-memory
representation of the actual DOM. This allows
ReactJS to efficiently update and render only the
components that have changed, instead of re-
rendering the entire page.
Environment
Setup
Environment Setup
⎊ ReactJS requires NodeJS to run
- Install NodeJS and npm (Node.js)

⎊ NPM stands for Node Package Manager


- You will need to install some node package through
npm.
- You can also use yarn for installing package.
- https://classic.yarnpkg.com/en/docs/install#windows-s
table
Environment Setup
⎊ Initialize a Project
We can pick one of the React frameworks to build a new
app or a new website fully with React.
- Create a react project with Vite :
npm create vite@latest
Environment Setup
⎊ Initialize a Project (cont.)

- Navigate to project directory :


cd <prject_name>

- Install the project dependencies :


npm install
Environment Setup
⎊ Initialize a Project (cont.)

- Start running the application:


npm run dev
Environment
Setup
⎊ Initialize a Project
(cont.)
After the installation of the
required project files, your
project structure may look
something like the right
picture.
Each file and folder will be
Environment Setup
⎊ Initialize a Project (cont.)
1. node_modules : it is a folder that contains all the
project’s dependencies installed by npm and
managed by a package.json file.
2. public : The public folder is where you put the
files that need to be publicly available, such as
images, fonts, and other static files.
Environment Setup
⎊ Initialize a Project (cont.)
1. src : has the source code and all React-related
code.
2. .gitignore : it is a file that tells Git not to monitor
certain files and folders.
3. eslint.config.js : configuration file for ESLint.
4. index.html : the main HTML file for the app. It’s
where the React application is mounted into a
Environment Setup
⎊ Initialize a Project (cont.)
5. package.json : this file lists your project’s
dependencies and scripts.
6. package-lock.json : it locks the versions of your
project’s dependencies.
7. README.MD : it is a markdown document with
numerous links and useful advice that will assist
you in using Create React App.
Environment Setup
⎊ Initialize a Project (cont.)
8. vite.config.js : it is the configuration file for Vite.
It allows us to customize the build process, define
plugins, define port, and set other project-specific
configurations.
JSX &
Components
JSX
⎊ JSX is a syntax extension for JavaScript that lets you
write HTML-like markup inside a JavaScript file. It is not
necessary to use it, however, here are some of the
benefits of using JSX with ReactJS :
- Improved readability : JSX makes it easy to see the
structure and hierarchy of your components, as well as
the props and state that they rely on.
JSX
- Stronger type checking : Because JSX gets transpiled
to JavaScript, you can use the type checker of your
choice to detect errors early.
- Reusability : With JSX, you can define reusable
components that can be composed together to create
more complex user interfaces.
JSX
⎊ The main differences between HTML and JSX are :
- You need to return a single parent element in JSX
- You can implement JS directly in JSX : it is possible
to write JavaScript directly by putting the JavaScript
code in curly braces { ... }.
- Write all HTML Attributes in camelCase in JSX.
JSX
⎊ The main differences between HTML and JSX are :
(cont.)
- All tags self-close in JSX : self-closing tags in HTML
can self-close without the slash before the right angle
bracket, that is <br /> could work as <br>. But in JSX,
you need to include the slash. JSX heavily relies on HTML
4 syntax.
- We cannot use if else statements inside JSX, instead we
JSX
⎊ Example
import React from "react";
export default function CalculateComponent() {
let value = 5;
return (
<>
<div>{value === 5 ? "It's five." : "Not
five"}</div>
</>
);
}
Components
- Components in React are the code blocks representing
the UI elements.
- These blocks are reusable and independent like
functions in JavaScript.
- Components make the task of building user interfaces
much easier.
Components
Components
⎊ Example

import React from 'react'

function OutputComponent() {
return (
<div>OutputComponent</div>
)
}
export default OutputComponent
Components
⎊ Importing and Exporting ReactJS Components
- There are 2 ways to export and import components (or
values) in ReactJS :
1. Named export and import
2. Default export and import
Components
⎊ Named Export
- To export multiple functions into another components as
a named export, we just need to use the export
keywords in front of the functions.
- We can use curly braces { } to export more than one
named export instead of exporting individually.
Components
⎊ Example
import React from "react";

export function CarComponent() {


return <div>CarComponent</div>;
}

export function MotorCycleComponent() {


return
<div>MotorCycleComponent</div>;
}
Components
⎊ OR
import React from "react";
function CarComponent() {
return <div>CarComponent</div>;
}
function MotorCycleComponent() {
return <div>MotorCycleComponent</div>;
}
export { CarComponent,
MotorCycleComponent };
Components
⎊ Named Import
- Once we define a component with the export keyword,
we can now access and import those exported functions
using the import keyword.
- We must enclose the functions or values in curly braces
{ … } and give them the same name as defined from
where they are exported.
Components
⎊ Named Import (cont.)
- We cannot change the name of the imported bindings
(bindings are nothing but functions, values, or classes).
- We can import multiple bindings into a single line of
code, separated by commas ( , ).
Components
⎊ Example
import { CarComponent, MotorCycleComponent }
from "./Components/CarComponent";
export default function App() {
return (
<div>
<CarComponent />
<MotorCycleComponent />
</div>);
}
Components
⎊ Default Export
- The default export is also used for exporting
components, values, classes, etc. in ReactJS, but only
one element can be exported to another component at
a time as a default export.
- In other words, a file can have only one default export.
- We just need to put export and default keywords in
front of the function.
Components
⎊ Example
import React from "react";
export default function CalculateComponent() {
let value = 18;
return (
<>
<div>{value === 18 ? "You're allowed to vote." :
"You're illegal."}</div>
</>);}
Components
⎊ Default Import
There are two main differences from the named import,
which are :
- We do not need to wrap the binding inside the curly
brackets.
- Can be given any name as the name of that exported
binding.
Components
⎊ Example

import CalculateComponent from


"./Components/CalculateComponent";

export default function App() {


return ( <div><CalculateComponent
/></div> );
}
List & Key
List
⎊ To render data from an array, we can use map( )
method.
import React from "react";
⎊ Example
export default function OutputComponent()
{
const numbers = [1, 2, 3, 4, 5];
const number = numbers.map((num) =>
num);
return <div>{number}</div>;
}
List
⎊ OR
import React from "react";
const numbers = [1, 2, 3, 4, 5];
export default function OutputComponent() {
return (
<div>
{numbers.map((num) => (
<p>{num}</p>
))}
</div>);
}
Key
⎊ Keys help React identify which items have changed, are
added, or are removed.
⎊ Example import React from "react";
const numbers = [1, 2, 3, 4, 5];
export default function OutputComponent() {
return (<div>{numbers.map((num, index) =>
(
<p key={index}>{num}</p>
))}
</div>); }
React Hooks
React Hooks
⎊ Introduction to Hooks
- Hooks are built-in React functions introduced in React
version 16.8.
- They allow you to use features of the React library like
lifecycle methods, state, and context in functional
components without having to worry about rewriting it
to a class.
React Hooks
⎊ Introduction to Hooks (cont.)
- Each React Hook name is prefixed with the word “use”.
- Although hooks generally replace class components,
there are no plans to remove classes from React.
React Hooks
⎊ When to use React Hooks
- If you write a functional component, and then you want
to add some state to it, previously you do this by
converting it to a class. However, now you can do it by
using a hook inside the existing function component.
React Hooks
⎊ Rules of using React Hooks
- Only call hooks at the top level of a component :
You shouldn’t use Hooks inside loops, conditions, or
nested functions.
- Only call hooks from React Functions : Never call
hooks from regular JavaScript functions. You can :
● Call Hooks from React functional components.
● Call Hooks from custom hooks.
useState Hook
⎊ useState Hook
- The useState Hook allows you to create, update, and
manipulate state inside functional components.
- The hook takes a single optional argument : an initial
value for that state.
useState Hook
⎊ useState Hook (cont.)
- The hook returns an array of two values :
● The first element is the state variable
● The second element is a function to update the state
⎊ What can state hold?
- The useState hook can be used to keep track of strings,
numbers, booleans, arrays, objects, and any
combination of these.
useState Hook
⎊ import
Example
React, { useState } from "react";
export default function CalculateComponent() {
const [number, setNumber] = useState(0);
return (
<>
<div>{number}</div>
<button
onClick={()=>setNumber(number+1)}>Increase</button>
<button
onClick={()=>setNumber(number-1)}>Decrease</button>
</>); }
useState Hook
⎊ Explanation
We can destructure the returned values from useState
as :
- The first value, number, is our current state.
- The second value, setNumber, is the function that is
used to update our state.
⎊ Note : these names are variables that can be named
anything you would like.
Component Life
Cycle
Component Life
Cycle
⎊ Every react component goes through the same
lifecycle :
- A component mounts when it’s added to the screen.
- A component updates when it receives new props or
state, usually in response to an interaction.
- A component unmounts when it’s removed from the
screen.
useEffect Hook
⎊ useEffect Hook
- The useEffect hook allows you to perform side effects
in your components.
- useEffect accepts two arguments. The second
argument is optional.
useEffect(<function>, <dependency>)
Syntax :
useEffect Hook
⎊ useEffect Hook (cont.)
- There are several ways to control when side effects run.
- We should always include the second parameter which
accepts an array. We can optionally pass dependencies
to useEffect in this array.
useEffect Hook
⎊ Example
1. No dependency passed (runs on every render) :
import React, { useEffect, useState } from "react";
export default function CalculateComponent() {
const [state, setState] = useState(0);
useEffect(() => {console.log("Runs on every render");});
return (<>
<div>{state}</div>
<button
onClick={()=>setState(state+1)}>Increase</button>
</>); }
useEffect Hook
2. An empty
import React, {array (runsuseState
useEffect, only on the "react";
} from first render) :
export default function CalculateComponent() {
const [state, setState] = useState(0);
useEffect(()=>{console.log("Runs on the first
render");},[]);
return (<>
<div>{state}</div>
<button
onClick={()=>setState(state+1)}>Increase</button>
</>);
}
useEffect Hook
3. Props or state values (runs on the first render
and any time any dependency value changes) :
import React, { useEffect, useState } from "react";
export default function CalculateComponent() {
const [state, setState] = useState(0);
const [value, setValue] = useState(1);
useEffect(() => {console.log("The value doesn't effect.");},
[state]);
return (<><p>{state}</p>
<button onClick={() => setState(state + 1)}>State</button>
<p>{value}</p>
<button onClick={() => setValue(value +
1)}>Value</button></>); }
useEffect Hook
⎊ Effect Cleanup
- Some effects require cleanup to reduce memory
leaks.
- Timeouts, subscriptions, event listeners, and other
effects that are no longer needed should be disposed.
- We do this by including a return function at the end
of the useEffect hook.
useEffect Hook
⎊ Note
- To make it more convenient with how the cleanup
function works, you need to install react router dom
which is used for navigation.
- Installation :
npm i react-router-dom
useEffect Hook
⎊ Example
//index.js
const
root=ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
useEffect Hook
⎊ Example (cont.)
//App.js
function App() {
return (
<>
<Routes>
<Route path="/" element={<HomepageComponent />} />
<Route path="/about" element={<AboutUsComponent
/>} />
</Routes>
</> );}
useEffect Hook
⎊ Example (cont.)
//AboutUsComponent.jsx
export default function AboutUsComponent() {
return (
<div>
<h1>AboutUsComponent</h1>
<NavLink to={"/"}>Go to Home page</NavLink>
</div>
);
}
useEffect Hook
⎊ Example (cont.)
//HomepageComponent.jsx
export default function HomepageComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
let countInterval = setInterval(() => {
setCount(count + 1); console.log(count); }, 1000);
return () => {
clearInterval(countInterval);
}; }, [count]);
useEffect Hook
⎊ Example (cont.)
//HomepageComponent.jsx
return (
<div>
<div>HomePage</div>
<NavLink to={"/about"}>Go to About
page</NavLink>
</div>
);
}
State & Props
State
⎊ What is state?
- A state is a variable that exists inside a component.
- It cannot be accessed and modified outside the
component.
- It can only be used inside the component.
- In short, state can be considered as private data.
- State is changeable.
Props
⎊ What are props?
- Props, short for “properties”, are a way to pass data
from a parent component to a child component in React.
- They are similar to function arguments and also similar
to HTML attributes.
Props
⎊ What are props? (cont.)
- Props are immutable, which means that once they are
passed to a component, they cannot be changed.
- Keep in mind that props are read-only.
State & Props
⎊ Example (Through data from parent to child
import React,
component) { useState } from "react";
import CalculateComponent from
- OutputComponent (Parent Component)
"./CalculateComponent";
export default function OutputComponent() {
const [string, setString] = useState("Hello
World");
return (
<div><CalculateComponent string={string}
/></div>
);
State & Props
⎊ Example (Through data from parent to child
component) (cont.)
- CalculateComponent (Child Component)
import React from "react";
export default function
CalculateComponent({ string }) {
return (
<>
<p>{string}</p>
</>);}
State & Props
⎊ Example (Through data from child to parent
component)
import React, { useState } from "react";
- OutputComponent (Parent Component)
import CalculateComponent from "./CalculateComponent";
export default function OutputComponent() {
const [num, setNum] = useState(12);
const cal = (childNum) => { setNum(num * childNum) };
return (
<div><CalculateComponent num={num} calculate={cal}
/></div>);
}
State & Props
⎊ Example (Through data from child to parent
component) (cont.)
- CalculateComponent (Child Component)
import React from "react";
export default function CalculateComponent({ num, calculate }) {
function handleSendNumToParent() { calculate(5) }
return ( <>
<p>{num}</p>
<button onClick={() =>
handleSendNumToParent()}>Result</button>
</>);}
State & Props
⎊ Differences between Props and State :
Props State
The data is passed from one The data is managed within
component to another. the component only.
It is immutable (cannot be It is mutable (can be
modified). modified).
Props are read-only. The state is both read and
write.
Props can be accessed by State cannot be accessed by
the child component. child components.
Thank You

You might also like