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

Unir 2 - 2. Components in React

Unit 2 covers building React applications including setting up the development environment, components, state, and building a time-logging app. The document discusses ReactJS being a declarative, efficient JavaScript library for building reusable UI components. It is component-based and responsible for the view layer. Reasons for using React include building UIs that improve app speed using a virtual DOM, component patterns that improve readability, and a large community. The document also covers React tools, versions, features, benefits and applications.

Uploaded by

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

Unir 2 - 2. Components in React

Unit 2 covers building React applications including setting up the development environment, components, state, and building a time-logging app. The document discusses ReactJS being a declarative, efficient JavaScript library for building reusable UI components. It is component-based and responsible for the view layer. Reasons for using React include building UIs that improve app speed using a virtual DOM, component patterns that improve readability, and a large community. The document also covers React tools, versions, features, benefits and applications.

Uploaded by

Sukruthi KC
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Unit 2: Full stack React

Contents
• Your first React Application
• Setting up the development environment
• What is a Component?
• Building Product
• Updating state and immutability
• Components:
• A time-logging app
• Building a static version of the app
• determining stateful components and initial states
• add inverse data flow, update and delete timers
What is ReactJS?
• ReactJS is a declarative, efficient, and flexible JavaScript library for building
reusable UI components.
• It is an open-source, component-based front end library which is responsible only for the
view layer of the application. It was initially developed and maintained by Facebook and
later used in its products like WhatsApp & Instagram.
• ReactJS is a simple, feature rich, component based JavaScript UI library. It can be used to
develop small applications as well as big, complex applications. ReactJS provides minimal
and solid feature set to kick-start a web application.
• React community compliments React library by providing large set of ready-made
components to develop web application in a record time.
• React community also provides advanced concept like state management, routing, etc., on
top of the React library.
What is ReactJS?
 ReactJS uses virtual DOM based mechanism to fill in data (views) in HTML
DOM.
 The virtual DOM works fast owning to the fact that it only changes
individual DOM elements instead of reloading complete DOM every time
 A React application is made up of multiple components, each responsible
for outputting a small, reusable piece of HTML. Components can be nested
within other components to allow complex applications to be built out of
simple building blocks.
 A component may also maintain internal state - for example, a TabList
component may store a variable corresponding to the currently open tab.
Why we use ReactJS?

• The main objective of ReactJS is to develop User Interfaces


(UI) that improves the speed of the apps. It uses virtual DOM
(JavaScript object), which improves the performance of the
app.
• The JavaScript virtual DOM is faster than the regular DOM. We can use ReactJS
on the client and server-side as well as with other frameworks.
• It uses component and data patterns that improve readability and helps to
maintain larger apps.
React versions

• The initial version, 0.3.0 of React is released on May, 2013 and the
latest version, 17.0.1 is released on October, 2020.
• The major version introduces breaking changes and the minor
version introduces new feature without breaking the existing
functionality.
Features, Benefits and Applications
• Features • Benefits • Applications
• The salient features • Few benefits of
of React library are • Few popular websites powered
using React library are as by React library are listed below −
as follows − follows −
• Solid base • Easy to learn • Facebook, popular social media
application
architecture • Easy to adept in modern
as well as legacy • Instagram, popular photo
• Extensible sharing application
architecture application
• Faster way to code a • Netflix, popular media
• Component based streaming application
library functionality
• Availability of large • Code Academy, popular online
• JSX based design number of ready-made training application
architecture component • Reddit, popular content sharing
• Declarative UI • Large and active application
library community
The CLI Tools
• React provides CLI tools for the developer to fast forward the creation,
development and deployment of the React based web application.
• React CLI tools depends on the Node.js and must be installed in your
system.
• If you have installed Node.js on your machine, check it using the below
command −
• node --version
• You could see the version of Nodejs you might have installed.
• My machine has the following version:

• If Nodejs is not installed, you can download and install by visiting


https://nodejs.org/en/download/
Toolchain
• To develop lightweight features such as form validation, model dialog, etc.,
• React library can be directly included into the web application through content
delivery network (CDN).
• For moderate to big application, it is advised to write the application as multiple
files and then use bundler such as webpack, parcel, rollup, etc., to compile and
bundle the application before deploying the code.
• React toolchain helps to create, build, run and deploy the React application. React
toolchain basically provides a starter project template with all necessary code to
bootstrap the application.
• Some of the popular toolchain to develop React applications are:
• Create React App − SPA oriented toolchain
• Next.js − server-side rendering oriented toolchain
• Gatsby − Static content oriented toolchain
• Tools required to develop a React application are −
• The serve, a static server to serve our application during development
• Babel compiler
• Create React App CLI
Describing the UI

• React is a JavaScript library for rendering user interfaces (UI). UI is built


from small units like buttons, text, and images.
• React lets you combine them into reusable, nestable components. From web
sites to phone apps, everything on the screen can be broken down into
components.
• React Components
• Building a React app is all about components.
• Components describe a part of the user interface
• They are reusable and can be nested inside the other components
• An individual React component can be thought of as a UI component in an app.
• Components are one of the core concepts of React.
• They are the foundation upon which you build user interfaces (UI), which makes them the
perfect place to start your React journey
More on Components
• Traditionally when creating web pages, web developers marked up
their content and then added interaction by sprinkling on some
JavaScript.
• This worked great when interaction was a nice-to-have on the web.
• Now it is expected for many sites and all apps.
• React puts interactivity first while still using the same technology:
• a React component is a JavaScript function that you
can sprinkle with markup.
Types of component
• Functional Components:
• Functional components are simply javascript functions.
• We can create a functional component in React by writing a javascript function.
• These functions may or may not receive data as parameters
• Class Components:
• The class components are a little more complex than the functional components.
• The functional components are not aware of the other components in your
program whereas the class components can work with each other.
• We can pass data from one class component to another class component.
• We can use JavaScript ES6 classes to create class-based components in React.
Example of functional component
import React from 'react'; • We call the ReactDOM.render() as the first
import ReactDOM from 'react-dom'; parameter.
• React then calls the component Welcome,
which returns <h1>Hello World!</h1>; as
// This is a functional component the result.
const Welcome = () => { • Then the ReactDOM efficiently updates
the DOM to match with the returned
return <h1>Hello World!</h1> element and renders that element to the
} DOM element with id as “root”.

ReactDOM.render(
<Welcome />,
document.getElementById("root")
);
Two Types of Components
• Stateless Functional Components
• Stateful Class Components

Class Welcome extends


React.Component {
render()
function Welcome(props) {
{ return <h1> Hello,props.name)
return <h1> Hello, {props.name} </h1>
</h1>
}
}
• Check few examples here
• https://codesandbox.io/s/silent-mountain-
p8mwhm?file=/form_component.js
• Form component into two smaller components, one for the input
field and another one for the button
Sample App.js
export default function Profile()
{
return (
<img src="https://i.imgur.com/MK3eW3Am.jpg"
alt="Katherine Johnson" />
)
}
• App.js
function Profile() {
return (
<img
src="https://encrypted-tbn2.gstatic.com/licensed-
image?q=tbn:ANd9GcSUPobOTWGGkexkI3nf8u8LFP65DSHycLqi52PJLG0IDhOHSHHPSs1iJUW09LLdUcQiKnoF93mTYz7tDaQ"
alt="Einstein"
/>
);
}

export default function Gallery() {


return (
<section>
<h1>Amazing scientists</h1>
<Profile />
<ul>
<li> Where wa he born? </li>
<li> What were his achievements? </li>
</ul>
<div>
<a href="https://en.wikipedia.org/wiki/Albert_Einstein"> AE </a>
</div>
</section>
);
}
• Note:
• Notice the difference in casing:
• <section> is lowercase, so React knows we refer to an HTML tag.
• <Profile /> starts with a capital P, so React knows that we want to use our
component called Profile.

• Nesting and organizing components


• Components are regular JavaScript functions, so you can keep multiple
components in the same file.
• This is convenient when components are relatively small or tightly related to each
other. If this file gets crowded, you can always move Profile to a separate file. You
will learn how to do this shortly on the page about imports.
• Because the Profile components are rendered inside Gallery—even several
times!—we can say that Gallery is a parent component, rendering each
Profile as a “child”.
• This is part of the magic of React: you can define a component once, and then use it
in as many places and as many times as you like.
Importing and Exporting Components

• The magic of components lies in their reusability:


• you can create components that are composed of other components.
• But as you nest more and more components, it often makes sense to start splitting them
into different files.
• The root component file
• In our example we first created a Profile Component and next the Gallery Component
• The Gallery Component renders it on the console
• However, all these live in a root component file, named App.js in this example.
• In Create React App, your app lives in src/App.js.
• Depending on your setup, your root component could be in another file, though.
• Note: If you use a framework with file-based routing, such as Next.js, your root
component will be different for every page
Exporting and importing a component
• Suppose you want to change the landing screen? How to achieve
it?
• It makes sense to move Gallery and Profile out of the root component file.
• This will make them more modular and reusable in other files.
• Follow the steps to move a component in three steps:
• Make a new JS file to put the components in.
• Export your function component from that file
• Import it in the file where you’ll use the component
• In our example now we will move both Profile and Gallery oved out of App.js into a
new file called Gallery.js.
• Now you can change App.js to import Gallery from Gallery.js:
Modularized!!
Gallery.js
App.js function Profile() {
return (
import Gallery from './Gallery.js'; <img src="https://i.imgur.com/QIrZWGIs.jpg" alt="Alan
L. Hart" /> );
export default function App()
}
{
export default function Gallery()
return ( <Gallery /> );
{ return
}
(
What does this code do?
• Imports Gallery as a default import from Gallery.js.
<section>
• Exports the root App component as a default export. <h1>Amazing scientists</h1> <Profile />
</section> );
}
What does this code do?
• Defines the Profile component which is only used within
the same file and is not exported.
• Exports the Gallery component as a default export.
Recap
• Step 1: Export the component
• The export default prefix is a standard JavaScript syntax (not specific to
React).
• It lets you mark the main function in a file so that you can later import it from
other files.
• Step 2: Define the function
• With function Profile() { } you define a JavaScript function with the name
Profile
• Step 3: Add markup
• The component returns an <img /> tag with src and alt attributes. <img /> is
written like HTML, but it is actually JavaScript under the hood! This syntax is
called JSX, and it lets you embed markup inside JavaScript.
Composing Components
• Create individual components and merge them to create a parent
component
• For example
• Creating individual components named Navbar, Sidebar, ArticleList and
merge them to create a parent component named App and then render
this App component.
import React from 'react';
// App Component
const App=()=>
import ReactDOM from 'react-dom';
{
return(
// Navbar Component
<div>
const Navbar=()=>
<Navbar />
{
<Sidebar />
return <h1>This is Navbar.< /h1>
<ArticleList />
}
</div>
);
// Sidebar Component
}
const Sidebar=()=> {
return <h1>This is Sidebar.</h1>
ReactDOM.render(
}
<App />,
document.getElementById("root")
// Article list Component
);
const ArticleList=()=>
{
return <h1>This is Articles List.</h1>
}
Decomposing Components
• Decomposing a Component means breaking down the component
into smaller components.
• Suppose we want to make a component for an HTML form that
includes textbox and button
import React from 'react';
import ReactDOM from 'react-dom';
const Form=()=>
{
return (
<div>
<input type = "text" placeholder = "Enter Text.." />
<br />
<br />
<input type = "text" placeholder = "Enter Text.." />
<br />
<br /> This code works well to create a form.
<button type = "submit">Submit</button>
But let us say now we need some other form with three
input fields. Can we write reusable code?
</div>
Lets check in the next slide
);
}
ReactDOM.render(
<Form />,
document.getElementById("root")
);
import React from 'react';
// Form component
import ReactDOM from 'react-dom';
const Form=()=>
{
// Input field component
return (
const Input=()=>
<div>
{
<Input />
return(
<Input />
<div>
<Button />
<input type="text" placeholder="Enter Text.." />
</div>
<br />
);
<br />
}
</div>
);
ReactDOM.render(
}
<Form />,
document.getElementById("root")
// Button Component
);
const Button=()=>
{
return <button type = "submit">Submit</button>;
}
Props
• The term 'props' is an abbreviation for 'properties' which refers to the
properties of an object.
• React Props are like function arguments in JavaScript and attributes in
HTML. Thus they are inputs that you pass into components.
• The props enable the component to access customised data, values, and
pieces of information that the inputs hold.
• Props are also how you pass data from one component to another, as
parameters.
• Eg:
1. const myElement = <Car brand="Ford" />; // adding property for car element
2. function Car(props)
{
return <h2>I am a { props.brand }!</h2>; // component receiving the brand as props
}
How you pass data from one component to another?
Let us look at three variants

1. Send the value as a string

import React from 'react';


import ReactDOM from 'react-dom/client';

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 />);
2. Send the variable name
function Car(props) {
return <h2>I am a { props.brand }!</h2>;
}

function Garage() {
const carName = "Ford";
return (
You can also send a
<> variable name
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}

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


root.render(<Garage />);
3.As a object
import React from 'react';
import ReactDOM from 'react-dom/client';

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

function Garage() {
const carInfo = { name: "Ford", model: "Mustang" };
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carInfo } />
</>
);
}

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


root.render(<Garage />);
import React from 'react';
import ReactDOM from 'react-dom';
// Parent Component
class Parent extends React.Component{
render(){
return(
<div>
<h2>You are inside Parent Component</h2>
<Child name="User" userId = “5555"/>
</div>
); } }

// Child Component
class Child extends React.Component{
render(){
return(
<div>
<h2>Hello, {this.props.name}</h2>
<h3>You are inside Child Component</h3>
<h3>Your user id is: {this.props.userId}</h3>
</div>
); } }

ReactDOM.render(
// passing props
<Parent />,
document.getElementById("root")
);
import React from 'react';
import ReactDOM from 'react-dom';
Can we pass default values using props?
// Component
class ExampleClass extends React.Component {
render() { • Yes, React provides us with
return (
<div> something called defaultProps for
{/* using default prop - title */}
<h1>This is {this.props.title}'s Website!</h1>
this purpose.
</div>
); • defaultProps:
}
}
• The defaultProps is a method that we
can use to store as much information
// Creating default props for as we want for a particular class, and
// ExampleClass Component
ExampleClass.defaultProps = { this information can be accessed
title: “Amazon’s site" from anywhere inside that particular
}
class.
ReactDOM.render( • Every piece of information you add
<ExampleClass />,
document.getElementById("root") inside the defaultProps, will be added
); as the prop of that class.
Stateful and Stateless Components in React
• First let us look into the state
• React State is integral to using React, especially when dealing with dynamic
components
• They are the heart of stateful vs stateless React component structures
• It allows updates and rendering of components based on user input or
backend changes.
• React’s State allows for efficient data flow in an application, providing the
necessary functionality for stateful and stateless components in React to
interact seamlessly
• State in ReactJS is an attribute of a component that can change over time. It
allows a component to create dynamic and interactive experiences. This,
however, doesn’t imply that all components should have state.
• In fact, determining whether a component needs to be stateful or
stateless is a significant design decision in React application
development.
• Stateful Components
• Stateful components, as their name implies, have a state.
• They are capable of tracking changes, have knowledge of past, current, and
potential future changes in themselves, and render their output accordingly.
• Stateful components are usually class components, but with the introduction
of hooks, functional components can also maintain state.
• Stateless Components
• On the other side, stateless components are those that calculate their
internal state but do not record or modify it. Stateless components
receive data through props and render it. They are typically used for
components that merely display data and don’t manage it. To further
understand the difference between stateless and stateful
components in React, a stateless component React example could be
a simple button or a list item.
• Can you use State in all components?
• Technically, yes.
• But should you?
• Not always.
• Points to Consider:
• If a component doesn’t need to know about its past or future states, it
doesn’t need State.
• Making such a component stateful unnecessarily can lead to complicated
code and potential performance issues.
• If a component’s output doesn’t depend on its state and can be
determined solely by its props, it should be a stateless component.
• Stateless components are easier to test and understand.
• Always start building a component as stateless and only
convert it to a stateful component if necessary. This
practice makes your components more flexible and maintainable.
Comparing Stateful and Stateless
Stateful Components Stateless Components

Components that have state and can change their


Definition Components that don’t have state and rely on props
own data

Syntax Class components Function components

State Can manage state


Cannot manage state
management using this.state and this.setState()

Props Can receive props from parent components Can receive props from parent components

Re-rendering Re-renders when state or props change Re-renders when props change

More complex and can be less performant due to Simpler and can be more performant since they don’t
Performance
managing state manage state

Have access to lifecycle methods


Lifecycle
like componentDidMount() and componentWillU Don’t have access to lifecycle methods
methods
nmount()

Ideal for complex components that need to Ideal for simpler components that just render UI based on
Usage
manage state props
Create a stateful component

• Example – program displaying current date and time.


• First, create a new react application, react-clock-app using Create React
App or Rollup bundler by following instruction in Creating a React
application chapter.
• Open the application in your favorite editor.
• Create src folder under the root directory of the application.
• Create components folder under src folder.
• Create a file, Clock.js under src/components folder and start editing.
• Import React library.
import React from 'react';
//Create Clock Component export default Clock;
class Clock extends React.Component {
// initialize state with current date and time
Next, create a file, index.js under the src folder
constructor(props) { and use Clock component.
super(props);
this.state = {
import React from 'react';
date: new Date()
} import ReactDOM from 'react-dom';
// use JavaScript method, setInterval and call setTime() method every second to import Clock from './components/Clock';
ensure that the component’s state is updated every second.
setInterval( () => this.setTime(), 1000);
}
ReactDOM.render(
// add setTime method to update the current time <React.StrictMode>
setTime() { <Clock />
console.log(this.state.date);
</React.StrictMode>,
this.setState((state, props) => (
{ document.getElementById('root')
date: new Date() );
} This is clock.js
)) }
render() {
return (
<div>
<p>The current time is {this.state.date.toString()}</p>
</div>
Next, create a file, index.js under the src folder and use Clock component.

import React from 'react';


import ReactDOM from 'react-dom';
import Clock from './components/Clock';

ReactDOM.render(
<React.StrictMode>
<Clock />
</React.StrictMode>,
document.getElementById('root')
);
Under the root folder and create index.html file.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Clock</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>

Next, run the application using npm command.


npm start
Open the browser and enter http://localhost:3000 in the address bar and press enter. The
application will show the time and update it every second.

You might also like