0% found this document useful (0 votes)
76 views101 pages

Reactfile

The document provides an introduction to React JS including why React JS, its advantages, running JavaScript in HTML, creating elements using React JS, JSX syntax, components and props, and using third-party packages like create-react-app. Key topics covered include React.createElement(), ReactDOM.render(), embedding variables and expressions in JSX, nesting JSX elements, reusable and composable components, and create-react-app's folder structure and tools.

Uploaded by

sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views101 pages

Reactfile

The document provides an introduction to React JS including why React JS, its advantages, running JavaScript in HTML, creating elements using React JS, JSX syntax, components and props, and using third-party packages like create-react-app. Key topics covered include React.createElement(), ReactDOM.render(), embedding variables and expressions in JSX, nesting JSX elements, reusable and composable components, and create-react-app's folder structure and tools.

Uploaded by

sai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

Introduction to React JS | Cheat Sheet

1. React JS

React JS is an open-source JavaScript library used to build user interfaces. It was developed by
Facebook.

1.1 Why React JS?

Performant websites

Fewer lines of code

Improves readability of code

Less time consuming

Open Source

Reusable code

1.2 Advantages of React JS

Easy to Learn
Large Community
Developer Toolset

2. Running JavaScript in HTML

We can run JavaScript in HTML using the HTML script element. It is used to include JavaScript in
HTML.

Example:

<body>

<div id="root"></div>

<script type="text/javascript">

const rootElement = document.getElementById("root");

const element = document.createElement("h1");

element.textContent = "Hello World!";

element.classList.add("greeting");

rootElement.appendChild(element);

</script>
</body>

Here the type attribute specifies the type of the script.

To include an external JavaScript file, we can use the HTML script element with the attribute src. The
src attribute specifies the path of an external JS file.

<script type="text/javascript" src="PATH_TO_JS_FILE.js"></script>

Note:

When the browser comes across a script element while loading the HTML, it must wait for the script
to download, execute it, and only then can it process the rest of the page.

So, we need to put a script element at the bottom of the page. Then the browser can see elements

If more than one script elements are in the HTML, the script elements will be executed in the order
they appear.

3. Creating Elements using React JS

3.1 React CDN

<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>

<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>

3.2 React.createElement()

The React.createElement() method is used to create an element using React JS. It is similar to the
document.createElement() method in regular JavaScript.

Syntax: React.createElement(type, props);


type - Tag names like div, h1 and p, etc.

props - Properties like className, onClick and id, etc.

Props are shorthand for properties. It is an optional argument.

Example:

<script type="module">

const elementProps = { className: "greeting", children: "Hello world!" };

const elementType = "h1";

const element = React.createElement(elementType, elementProps);


</script>

Note:

The type attribute value of the HTML script element should be module to run React JS.

3.3 ReactDOM.render()

The ReactDOM.render() method is used to display the React element.

Syntax: ReactDOM.render(reactElement, container);


reactElement - What to render

container - Where to render

Example:

<body>

<div id="root"></div>

<script type="module">

const elementProps = { className: "greeting", children: "Hello world!" };

const elementType = "h1";

const element = React.createElement(elementType, elementProps);

ReactDOM.render(element, document.getElementById("root"));

</script>

</body>

4. JSX

React JS introduced a new HTML like syntax named JSX to create elements.

Syntax: const element = <h1 className="greeting">Hello World</h1>;

The above JSX element compiles to,

const elementProps = { className: "greeting", children: "Hello world!" };

const element = React.createElement("h1", elementProps);

Warning

In JSX, HTML tags always need to be closed. For example, <br />, <img />.
4.1 Babel

JSX is not JavaScript. We have to convert it to JavaScript using a code compiler. Babel is one such
tool.

It is a JavaScript compiler that translates JSX into regular JavaScript.

Example:

<script type="text/babel">

const elementProps = { className: "greeting", children: "Hello world!" };

const element = React.createElement("h1", elementProps);

const element = <h1 className="greeting">Hello World</h1>;

ReactDOM.render(element, document.getElementById("root"));

</script>

Note:

For JSX, the type attribute value of the HTML script element should be text/babel.

For providing class names in JSX, the attribute name should be className.

Differences between HTML and JSX :

HTML JSX

class className

for htmlFor

4.2 Embedding Variables and Expressions in JSX

We can embed the variables and expressions using the flower brackets {}.

Embedding variables in JSX:

<body>

<div id="root"></div>

<script type="text/babel">

const name = "Rahul";


const className = "greeting";

const element = <h1 className="greeting">Hello World</h1>;

const element = <h1 className={className}>Hello {name}!</h1>;

ReactDOM.render(element, document.getElementById("root"));

</script>

</body>

Embedding Expressions in JSX:


<body>

<div id="root"></div>

<script type="text/babel">

const fullName = (user) => user.firstName + " " + user.lastName;

const user = { firstName: "Rahul ", lastName: "Attuluri" };

const element = <h1 className="greeting"> Hello, {fullName(user)}!</h1>;

ReactDOM.render(element, document.getElementById("root"));

</script>

</body>

4.3 Nesting JSX elements

The ReactDOM.render() method returns only one element in render. So, we need to wrap the
element in parenthesis when writing the nested elements.

Example:

<body>

<script type="text/babel">

const element = (

<div>

<h1 className="greeting">Hello!</h1>

<p>Good to see you here.</p>

</div>

);
ReactDOM.render(element, document.getElementById("root"));

</script>

</body>

Components & Props | Cheat Sheet


1. Component

A Component is a JS function that returns a JSX element.

Syntax: const Welcome = () => <h1 className="message">Hello, User</h1>;

The component name should always start with a capital letter as react treats the components
starting with lowercase letters as HTML elements.

Example:

<script type="text/babel">

const Welcome = () => <h1 className="message">Hello, User</h1>;

ReactDOM.render(<Welcome />, document.getElementById("root"));

</script>

We can call the function with self-closing tags as shown above <Welcome />

1.1 Properties (Props)

React allows us to pass information to a component using props.

1.1.1 Passing Props

We can pass props to any component as we declare attributes for any HTML element.

Syntax: <Component propName1="propValue1" propName2="propValue2" />

Example:

const Welcome = () => <h1 className="message">Hello, User</h1>;

ReactDOM.render(
<Welcome name="Rahul" greeting="Hello" />,
document.getElementById("root")
);

1.1.2 Accessing Props

The components accept props as parameters and can be accessed directly.


Syntax: const Component = (props) => {
// We can access props here
};

Example:
const Welcome = (props) => {
const { name, greeting } = props;
return (
<h1 className="message">
{greeting}, {name}
</h1>
);
};

ReactDOM.render(
<Welcome name="Rahul" greeting="Hello" />,
document.getElementById("root")
);

1.2 Component is Reusable

A Component is a piece of reusable code that can be used in various parts of an application.

Example:
const Welcome = (props) => {
const { name, greeting } = props;
return (
<h1 className="message">
{greeting}, {name}
</h1>
);
};

ReactDOM.render(
<div>
<Welcome name="Rahul" greeting="Hello" />
<Welcome name="Ram" greeting="Hi" />
</div>,
document.getElementById("root")
);

1.3 Component is Composable

We can include a component inside another component.

Example:

const Welcome = (props) => {


const { name, greeting } = props;
return (
<h1 className="message">
{greeting}, {name}
</h1>
);
};

ReactDOM.render(
<div>
<Welcome name="Rahul" greeting="Hello" />
<Welcome name="Ram" greeting="Hi" />
</div>,
document.getElementById("root")
);

2. Third-party Packages

Creating a real-world app involves lot of setup because a large number of components need to
be organised.

Facebook has created a third-party package, create-react-app, to generate a ready-made React


application setup.

2.1 create-react-app

Installation Command: npm install -g create-react-app

It installs create-react-app globally in our environment.

2.1.1 Creating a React Application

Example: create-react-app myapp --use-npm

2.1.2 React Application Folder Structure

public/folder: Where we will keep assets like images, icons, videos etc
src/folder: Where we will do the majority of our work. All of our React components will
placed here.
node_modules
package-lock.json

node_modules:

This directory contains dependencies and sub-dependencies of packages used by the current react app,
as specified by package.json.

package-lock.json:

This file contains the exact dependency tree installed in node_modules. This provides a way to
ensure every team member have the same version of dependencies and sub-dependencies.

The index.js in the path src/folder/ is a starting point to the application. App.js, App.css are imported
in this file.
2.1.3 Starting a React Application

Run the below command from the React application directory.

Command : npm start

You can view the application in the URL http://localhost:3000 in your browser.

Note:All the ES6 Modules should be named with .js extension.

2.2 Pre-Configured tools

The create-react-app comes pre-configured with:

Live editing: Allows React components to be live reloaded.


ESLint: Analyzes source code to report programming errors, bugs, and syntax errors.
Prettier: Enforces a consistent style for indentation, spacing, semicolons and quotes, etc.
Babel: Compiles JSX into Regular JavaScript
Webpack: Stitches together a group of modules into a single file (or group of files). This
process is called Bundling.

Lists & Keys | Cheat Sheet


1. Keys

Keys help React to identify which items have changed, added, or removed. They should be given to
the elements inside the array for a stable identity.

The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
Most often, we would use IDs (uniqueNo) from our data as keys.

Example:

const userDetails = [
{
uniqueNo: 1,
imageUrl:
'https://assets.ccbp.in/frontend/react-js/esther-howard-img.png',
name: 'Esther Howard',
role: 'Software Developer'
}
]

Note
Keys used within arrays should be unique among their siblings. However, they don't need to
be unique in the entire application.
1.1 Keys as Props

Keys don't get passed as a prop to the components.

Example:

const UserProfile = props => {


const {userDetails} = props
const {imageUrl, name, role, key} = userDetails
console.log(key) // undefined

return (
<li className="user-card-container">
<img src={imageUrl} className="avatar" alt="avatar" />
<div className="user-details-container">
<h1 className="user-name"> {name} </h1>
<p className="user-designation"> {role} </p>
</div>
</li>
)
}
export default UserProfile

If we need the same value in the component, pass it explicitly as a prop with a different name.

Example:

const UsersList = userDetailsList.map((userDetails) =>


<UserProfile
key={userDetails.uniqueNo}
uniqueNo={userDetails.uniqueNo}
name={userDetails.name} />
);

Note:

React Error - ENOSPC: System limit for the number of file watchers reached

Since create-react-app live-reloads and recompiles files on save, it needs to keep track of all project
files.

To fix the error, run the below commands in the terminal:

Insert the new value into the system config


echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Check that the new value was applied


cat /proc/sys/fs/inotify/max_user_watches

Config variable name (not runnable)


fs.inotify.max_user_watches=524288
Class Component and State | Cheat Sheet
1. Components

There are two ways to write React Components.

They are:

Functional Components

Class Components

1.1 Functional Components

These are JavaScript functions that take props as a parameter if necessary and return react element
(JSX).

const Welcome = () => <h1>Hello, User</h1>;

export default Welcome;

1.2 Class Components

These components are built using an ES6 class.

To define a React Class Component,

Create an ES6 class that extends React.Component.


Add a single empty method to it called render().

1.2.1 extends

The extends keyword is used to inherit methods and properties from the React.Component.

1.2.2 render()

The render() method is the only required method in a class component. It returns the JSX element.

Syntax:
import { Component } from "react";

class MyComponent extends Component {

render() {

return JSX;

}
Use this.props in the render() body to access the props in a class component.

class Welcome extends Component {

render() {

const { name } = this.props

return <h1>Hello, {name}</h1>

Note
The component name should always be in the pascal case.

2. React Events

Handling events with React elements is very similar to handling events on DOM elements. There are
some syntax differences:

1. React events are named using camelCase, rather than lowercase.

Example:

HTML JSX

onclick onClick

onblur onBlur

onchange onChange

2. With JSX, you pass a function as the event handler rather than a string.

Example: <button onclick="activateLasers()">Activate Lasers</button>


<button onClick={activateLasers}>Activate Lasers</button>

We should not call the function when we add an event in JSX.

class MyComponent extends Component {

handleClick = () => {

console.log("clicked")
}

render() {

return <button onClick={this.handleClick()}>Click Me</button>

In the above function, the handleClick is called instead of passed as a reference.

class MyComponent extends Component {

handleClick = () => {

console.log("clicked")

render() {

return <button onClick={this.handleClick}>Click Me</button>

In the above function, the handleClick is passed as a reference. So, the function is not being called
every time the component renders.

Providing Arrow Functions

To not change the context of this, we have to pass an arrow function to the event.

Example1:

class MyComponent extends Component {

handleClick() {

console.log(this) // undefined

render() {

return <button onClick={this.handleClick}>Click Me</button>

Example2:
class MyComponent extends Component {

handleClick = () => {

console.log(this) // MyComponent {...}

render() {

return <button onClick={this.handleClick}>Click Me</button>

3. State

The state is a JS object in which we store the component's data that changes over time.

When the state object changes, the component re-renders.

Intialising State:

class Counter extends Component {

state = { count: 0 }

render() {

const { count } = this.state;

return <p className="count">{count}</p>;

3.1 Updating State

We can update the state by using setState(). We can provide function/object as an argument to set
the state.

Providing Function as an Argument:

Syntax: this.setState( prevState => ({... }) )


Here the previous state is sent as a parameter to the callback function.

onIncrement = () => {

this.setState((prevState) =>

console.log(`previous state value ${prevState.count}`)


)

3.2 State Updates are Merged

State updates are merged. It means that when you update only one key-value pair in the state
object, it will not affect the other key-value pairs in the state object.

Example:

// For example let's say your state is as followed:

state = { key1 : value1, key2 : value2 }

// if you use this.setState such as :

this.setState((prevState) => ({ prevState.key1 : value3 }))

// your new state will be :

state = { key1 : value3, key2 : value2 }

3.3 Functional Components vs Class Components

Functional Components Class Components

Renders the UI based on props Renders the UI based on props and state

Use Class Components whenever the state is required. Otherwise, use the Functional components

Conditional Rendering | Cheat Sheet


1 . Conditional Rendering

Conditional Rendering allows us to render different elements or components based on a condition.

Different ways to implement Conditional Rendering are:

Using an If...Else Statement

Using Element Variables

Using Ternary Operators


Using Logical && Operator

1.1 Using an If...Else Statement

import { Component } from "react"

import './App.css'

class App extends Component {

state = { isLoggedIn: true }

renderAuthButton = () => {

const {isLoggedIn} = this.state

if (isLoggedIn === true) {

return <button>Logout</button>

return <button>Login</button>

render() {

return (

<div className="container">

{this.renderAuthButton()}

</div>

export default App

1.2 Using Element Variables

import { Component } from "react"

import './App.css'

class App extends Component {

state = { isLoggedIn: true }


render() {

const { isLoggedIn } = this.state

let authButton

if (isLoggedIn) {

authButton = <button>Logout</button>

} else {

authButton = <button>Login</button>

return (

<div className="container">

<h1>React JS</h1>

{authButton}

</div>

export default App

1.3 Using Ternary Operators

import { Component } from "react"

import './App.css'

class App extends Component {

render() {

const { isLoggedIn } = this.state

return (

<div className="container">

{isLoggedIn ? <button>Logout</button> : <button>Login</button>}

</div>
)

export default App

1.4 Using Logical && Operator

import { Component } from "react"

import './App.css'

class App extends Component {

render() {

const { isLoggedIn } = this.state

return (

<div className="container">

{isLoggedIn && <button>Logout</button>}

{!isLoggedIn && <button>Login</button>}

</div>

export default App

Note: Conditional Rendering can be achieved using inline styles or adding classes with CSS display
property with value none. However, it is not preferable.

2. Default Props

defaultProps is a property in React Component used to set default values for the props. This is
similar to adding default parameters to the function.

Syntax:
// Component Definition

ComponentName.defaultProps = {

propName1: "propValue1",
propName2: "propValue2"

// Exporting Component

Example:

File: src/Welcome/index.js

const Welcome = (props) => {

const { name, greeting } = props;

return (

<h1 className="message">

{greeting}, {name}

</h1>

);

};

Welcome.defaultProps = {

name: "Rahul",

greeting: "Hello"

};

export default Welcome;

File: src/App.js
import { Component } from "react";

import Welcome from "./Welcome";

class App extends Component {

state = { isLoggedIn: true };

render() {

const { isLoggedIn } = this.state;

return (

<div className="container">
<Welcome greeting="Hello" />

</div>

);

export default App;

Note
While accessing the props, the correct prop name should be given.

Class Component and State | Part 2 | Cheat Sheet


1. setState() Object Syntax

The setState() object syntax can be used while updating the state to the value that is independent of
the previous state.

Syntax: this.setState(
{propertyName1: propertyValue1},

{propertyName2: propertyValue2}

// and many more...

);

1.1 Callback vs Object

Callback: this.setState(prevState => {


return { count: prevState.count + 1 };

});

It is used while updating the state to a value, which is computed based on the previous state.

Object: this.setState({ quantity: 2 });


It is used while updating the state to a static value.

2. Sending Function as Callback

We can pass functions as props to child components.

Syntax: <ComponentName functionName={this.functionName} />


3. Input Element

In React, the Input Element Value can be handled in two ways:

Controlled Input

Uncontrolled Input

3.1 Controlled Input

If the Input Element value is handled by a React State then it is called Controlled Input. Controlled
Inputs are the React Suggested way to handle Input Element value.

Example:
import {Component} from 'react'

class App extends Component {

state = {

searchInput: '',

onChangeSearchInput = event => {

this.setState({

searchInput: event.target.value,

})

render() {

const {searchInput} = this.state

return (

<input

type="text"

onChange={this.onChangeSearchInput}

value={searchInput}

/>

}
export default App

3.2 Uncontrolled Input

If the Input Element value is handled by the browser itself then it is called Uncontrolled Input.

Uncontrolled inputs are like traditional HTML form inputs. Its value can only be set by a user, but
not programmatically. However, in controlled input value is programmatically handled using React
State.

Example: <input type="text" />


Authentication & Authorization | Cheat Sheet
1. Client-Server Communication

1.1 Authentication

Authentication is the process of verifying a user's identity.

1.2 Authorization

Authorization is the process of verifying whether the user is authenticated and permitted to perform
some actions like accessing resources, etc.

Example:
After successful authentication, employees are only allowed to access certain resources based on their
roles.

Admin can Read, Create, Delete, and Update the Resources


User can only Read and Create the Resources
2. Authentication Flow

3. Route Parameters

When a component is rendered by the Route, some additional props are passed.

They are:

match

history

location

3.1 History

The history object has some methods to control the navigation in the browser, and it also maintains
the history of the routes we navigated.

It has the following methods to control the navigation in the browser:

push()
replace()
go()
goBack()
goForward(), etc.

The history.push() and history.replace() methods are used to navigate to other routes
programmatically.

3.1.1 history.push()

With the history.push() method, the user can go forward and backwards in the browser, and the
URL will change.
Syntax: history.push("PATH");

3.1.2 history.replace()

The history.replace() method replaces the current URL with new one. The user can't go backwards
to the previous URL.

Syntax: history.replace("PATH");

Authentication & Authorization | Part 2 | Cheat Sheet


1. JWT Token

JSON Web Token is a standard used to create Access Tokens. These access tokens are also
called JWT Tokens.

The client uses these access tokens on every subsequent request to communicate with the
Server.

Note
While making HTTP Request, we have to send an access token in the HTTP Headers with
the key Authorization.

Example:
Authorization: Bearer jwt_token

1.1 Storing JWT Token in State

When we store the JWT Token in the state,

On page refresh, the JWT token won't be available

It is difficult to pass state information to every component

2. Storage Mechanisms

Client-Side Data Storage

o Storing Data on the Client

Server-Side Data Storage

o Storing Data on the Server using some kind of Database

Different types of Client-Side data storage mechanisms are:


Local Storage

Cookies

Session Storage

IndexedDB, etc.

3. Cookies

A cookie is a piece of data that is stored on the user's computer by the web browser.

A cookie is made up of:

Name & Value

the visitor quits the browser.


D

you want to retrieve the cookie from any directory or page.


only be
retrieved with a secure server. If this field is blank, no such restriction exists, etc.

3.1 Why Cookies?

With cookies, we can set the expiry duration.

Examples:

Banking Applications - Cookies get expired in minutes

Facebook - Cookies get expired in months or years

3.2 Cookies vs Local Storage

Cookies Local Storage

We can set an expiration for Cookies Local storage data never expires

Cookies can store up to 4KB of data Local Storage can store up to 5 to 10 MB of data

3.3 Third Party Package js-cookie

JavaScript can read, create, modify, and delete the cookies.

NPM contains a js-cookie, a third-party package to manipulate cookies easily.


Installation Command: npm install js-cookie save

js-cookie methods are:

Cookies.set()- It is used to set the cookie

Cookies.get()- It is used to get the cookie

Cookies.remove()- It is used to remove the cookie

3.3.1 Cookies.set()

Syntax:

Cookies.set('CookieName', 'CookieValue', {expires: DAYS});

Example: Cookies.set('ACCESS_TOKEN', 'Us1L90PXl...', {expires: 1});


3.3.2 Cookies.get()

It returns undefined if the cookie expires or does not exist.

Syntax: Cookies.get('CookieNa me');

Example: Cookies.get('ACCESS_TOKEN');
3.3.3 Cookies.remove()

Syntax: Cookies.remove('CookieName');

Example: Cookies.remove('ACCESS_TOKEN');

4. Redirect Component

The react-router-dom provides the Redirect component. It can be used whenever we want to
redirect to another path.

Syntax: <Redirect to="PATH" />

Example: <Redirect to="/login" />

4.1 Redirect Component vs history Methods


Use the Redirect Component when you have to stop displaying UI and navigate to a
route.Ex: Inside Class Component - render()
In all other cases, use history.push() or history.replace() syntax Ex: onSubmit, onClick event
callback functions

Note: The Redirect component uses the history push and replace methods behinds the scene.
5. withRouter

The history prop will be available for only components which are directly given for
Route.
To provide history prop to other components, we can wrap it with the withRouter
function while exporting it.

Example:

import { withRouter} from 'react-router-dom'

...

export default withRouter(ComponentName)

Authentication & Authorization | Part 3 | Cheat Sheet

1.Router Switch

Switch can have any React Component inside it

Route
User defined Component
Redirect

2. Wrapper Component

Redirection Logic can be reused by separating out into a React Component called Wrapper
Component. Each route will be wrapped with it.

2.1 Protected Route

ProtectedRoute is the Wrapper Component which returns Home Route Component.

File: src/components/ProtectedRoute/index.js

import { Route, Redirect } from "react-router-dom";

import Cookies from "js-cookie";

const ProtectedRoute = (props) => {

const token = Cookies.get("jwt_token");

if (token === undefined) {


return <Redirect to="/login" />;

return <Route {...props} />;

};

export default ProtectedRoute;

setState() - Callback Function

The setState() is asynchronous, it takes an optional callback parameter that can be used to
make updates after the state is changed.

Syntax this.setState({property1: value1,...}, callbackFunction)

2. React Icons

react-icons is a third-party package contains bundle of icons like bootstrap, font


awesome, material icons etc..,
Check react-icons website here .

2.1 Installing React Icons

This below command installs all the react-icons library in your React project

Command: npm install react-icons

2.2 Searching React Icons

Click on the Icon to copy the Icon Name.


2.3 Importing React Icons

The First letters of the icon indicates the category of the Icon.
Each category of Icons have import statements separately, go to the category and
copy the import statement.

Example:

import { BsFilterRight } from "react-icons/bs";

import { FaFacebookF } from "react-icons/fa";

import { MdDelete } from "react-icons/md";

const ReactIcon = (props) => {

return (

<div>

<BsFilterRight />

<FaFacebookF />

<MdDelete />

</div>

);

};

export default ReactIcon;


Debugging using Developer tools | Cheat Sheet
Debugging

Debugging is the process of finding & fixing the bugs in the code.

We can debug using:

Browser Developer Tools

React Developer Tools

Browser Developer Tools

These are the tools provided by the browsers to debug the application loaded in the web browser.

Using Browser Developer Tools, we can:

View the source code (HTML, CSS, and JS)

View and change CSS

View logged messages in the console

Run JavaScript in the console

Check the responsiveness of an application, etc.

React Developer Tools

For React Developer Tools, we can install the React Developer Tools Extension for Google Chrome.

On-Demand Session | Part 2 | Cheat Sheet


1. Third-Party Packages

UUID (Universally Unique IDentifier)

Using the UUID package, we can generate a unique id

1.1 Installing UUID

Command: npm install uuid

1.2 Importing of UUID

UUID package provides uuidv4(), which returns a unique id whenever it is called.

import {v4 as uuidv4} from 'uuid'


2. Best Practice

The state should be immutable.

The best practice is to create a new array/object from the array/object in the previous state
using the spread operator.

this.state.contactsList = initialContactsList-----------------------------> wrong syntax

this.state.contactsList.push(...) -------------------------> wrong syntax

this.setState(prevState => ({

contactsList: [...prevState.contactsList, newContact ], ------------------------------> correct syntax

}))

2.1 Updating a Property of an Item inside List

We should not update the property of a list item directly. To update the property of a list item, we
should create a new object and return it to the list.

Syntax: {...object, newItem}

Component Life Cycle | Cheat Sheet


1. Component Life Cycle Phases

Every React Component goes through three phases throughout its lifetime:

Mounting Phase

Updating Phase

Unmounting phase

2. Mounting Phase

In this phase, the instance of a component is created and inserted into the DOM.

2.1 Methods

We mainly use the three methods. The three methods are called in the given order:

constructor()
render()
componentDidMount()
2.1.1 constructor()

The constructor() method is used to set up the initial state and class variables.

Syntax: constructor(props) {
super(props)

//state and class variables

We must call the super(props) method before any other statement. Calling super(props)
makes sure that constructor() of the React.Component gets called and initializes the
instance.

Initialising State through props


constructor(props) {

super(props)

this.state = { date: props.date }

2.1.2 render()

The render() method is used to return the JSX that is displayed in the UI.

2.1.3 componentDidMount()

The componentDidMount() method is used to run statements that require that the
component is already placed in the DOM.

Example: set timers, initiate API calls, etc.

3. Updating Phase

In this phase, the component is updated whenever there is a change in the component's state.

3.1 Methods

3.1.1 render()

The render() method is called whenever there is a change in the component's state.

4. Unmounting Phase

In this phase, the component instance is removed from the DOM.


4.1 Methods

4.1.1 componentWillUnmount()

The componentWillUnmount() method is used to cleanup activities performed.

Example: clearing timers, cancelling API calls, etc.

Routing using React Router | Cheat Sheet


1. Web Apps

Web Apps are of two types, based on how we get content:

Multi-page application (MPA)

Single-page application (SPA)

1.1 Multi-page application (MPA)

Every URL is associated with corresponding resources (HTML, CSS, JS).

The browser downloads these resources when you access them or navigate between
URLs.

1.2 Single-page application (SPA)

All URLs are associated with a single HTML page.

On navigating we only get the additional content (Component - HTML, CSS, JS).

1.2.1 Advantages of using Single-page application (SPA)

Faster Page loading - since they load only necessary Component (HTML, CSS, JS)
resources on subsequent requests.

React is mainly used to build Single-page applications.

2. React Router

In React, we build Single-page applications using React Router.

To implement routing, React Router provides various components:

BrowserRouter
Link
Route
Switch
2.1 BrowserRouter

To add routing wrap all the Components with BrowserRouter.

Syntax: <BrowserRouter>
<Component 1>

<Component 2>

...

</BrowserRouter>

2.2 Link

Link Component creates hyperlinks that allows to navigate around in application.

Syntax: <Link to="Path"> Display Text</Link>

The to prop specifies absolute path.

2.3 Route

The Route component renders specific UI component when path matches current URL.

Syntax: <Route path="Path" component={Component} />


2.3.1 Exact

Renders the route if path matches exactly the current url

Syntax : <Route exact path="Path1" component={Component1} />

Note
If user enters undefined Path, the Component be rendered

2.3 Switch

The Switch component will only render the first route that matches the path. If no path
matches, it renders the Not Found component.

Syntax:
<Switch>

<Route path="Path1" component={Component1} />

<Route path="Path2" component={Component2} />

<Route component={NotFound} />


</Switch>

3. Routing Example

File: src/App.js
import { BrowserRouter, Route, Switch } from "react-router-dom"

import NotFound from "./components/NotFound";

...

const App = () => (

<BrowserRouter>

<Header />

<Switch>

<Route exact path="/" component={Home} />

<Route exact path="/about" component={About} />

<Route exact path="/contact" component={Contact} />

<Route component={NotFound} />

</Switch>

</BrowserRouter>

export default App

File: src/components/Header/index.js
import { Link } from "react-router-dom";

...

const Header = () => (

...

<ul className="nav-menu">

<li>

<Link className="nav-link" to="/">Home</Link>


</li>

<li>

<Link className="nav-link" to="/about">About</Link>

</li>

<li>

<Link className="nav-link" to="/contact">Contact</Link>

</li>

</ul>

...

Routing using React Router | Part 2 & 3 | Cheat Sheet


1 . API Calls

In General we make API Calls inside componentDidMount() render().

1.1 Fetch

fetch is a promise-based API which returns a response object. In the backend, we use snake_case for
naming conventions.

2. Route Props

When a component is rendered by the Route, some additional props are passed

match
location
history
2.1 Match

The match object contains the information about the path from which the component is rendered.
More React Concepts | Cheat Sheet

1. Reconciliation

1.1 Virtual DOM

A Virtual DOM is a JS object, which is the virtual representation of an HTML


DOM.
Whenever new elements are added to the UI, a virtual DOM is created

React compares new virtual DOM with current virtual DOM, and the difference will be
efficiently updated to HTML DOM. So, the Virtual DOM helps to render the UI more
performantly.

React only updates what's necessary. This process is known as Reconciliation.

2. React Batch Updating

React combines multiple setState() calls into single update.


Example:

import { Component } from "react"

class Counter extends Component {

state = { count: 0 }

onIncrement = () => {

this.setState((prevState) => ({ count: prevState.count + 1 }))

this.setState((prevState) => ({ count: prevState.count + 1 }))

this.setState((prevState) => ({ count: prevState.count + 1 }))

render() {

const { count } = this.state

console.log("render() called")

return (

<>

<p className="count">Count {count}</p>

<button onClick={this.onIncrement}>Increase</button>

</>

}
export default Counter

In the above example, the render is called only once as React combines multiple setState() calls into
a single update.

3. setState() Syntax

3.1 Object Syntax

Object Syntax is used while updating the state to a value.

this.setState({

count: 5,

})

3.2 Callback Syntax

Callback Syntax is used while updating the state to a value that is computed based on the previous
state.

Syntax: this.setState((prevState) => ({ count: prevState.count + 1 }))

3.3 Object Syntax vs Callback Syntax

Object Syntax:

import { Component } from "react"

class Counter extends Component {

state = { count: 0 }

onIncrement = () => {

this.setState({ count: this.state.count + 1 })

this.setState({ count: this.state.count + 1 })

this.setState({ count: this.state.count + 1 })

render() {

const { count } = this.state


return (

<>

<p className="count">Count {count}</p>

<button onClick={this.onIncrement}>Increase</button>

</>

export default Counter

When the HTML button element is clicked, the value of the state variable count is 1.

When the Object Syntax is used, this.state.count is same for every setState statement as setState is
asynchronous.

Callback Syntax:

import { Component } from "react"

class Counter extends Component {

state = { count: 0 }

onIncrement = () => {

this.setState((prevState) => ({ count: prevState.count + 1 }))

this.setState((prevState) => ({ count: prevState.count + 1 }))

this.setState((prevState) => ({ count: prevState.count + 1 }))

render() {

const { count } = this.state

return (

<>

<p className="count">Count {count}</p>


<button onClick={this.onIncrement}>Increase</button>

</>

export default Counter

When the HTML button element is clicked, the value of the state variable count is 3.

The setState callback function receive prevState as an argument. So, it will receive an updated state
value when it is executed.

4. Children Prop

The children is a special prop that is automatically passed to every React Component.

The JSX Element/Text included in between the opening and closing tags are considered children.

4.1 Passing Text as Children

File: src/components/Post/index.js

import "./index.css"

import SocialButton from "./SocialButton"

const Post = () => (

<div className="post-container">

<p className="paragraph">Hooks are a new addition</p>

<SocialButton>Like</SocialButton>

</div>

export default Post

4.2 Accessing Children

File: src/components/SocialButton/index.js

import "./index.css"

const SocialButton = (props) => (

<button className="social-button">{props.children}</button>
)

export default SocialButton

5. Controlled vs Uncontrolled Input

In React, the Input Element value can be handled in two ways:

Controlled Input
Uncontrolled Input

5.1 Controlled Input

If the Input Element value is handled by a React State, then it is called Controlled Input.

It is the React Suggested way to handle the Input Element value.

Example:

import { Component } from "react"

class App extends Component {

state = {

searchInput: "",

onChangeSearchInput = (event) => {

this.setState({

searchInput: event.target.value,

})

render() {

const { searchInput } = this.state

return (

<>

<input

type="text"

onChange={this.onChangeSearchInput}
value={searchInput}

/>

<p>{searchInput}</p>

</>

export default App

5.2 Uncontrolled Input

If the Input Element value is handled by the browser itself, then it is called Uncontrolled Input.

Example:

import { Component } from "react"

class App extends Component {

state = {

searchInput: "",

onChangeSearchInput = (event) => {

this.setState({

searchInput: event.target.value,

})

render() {

const { searchInput } = this.state

return (

<>

<input type="text" onChange={this.onChangeSearchInput} />

<p>{searchInput}</p>
</>

export default App

6. Props vs State

The props and state are plain JS objects.

The props and state changes trigger the render method.

Props State

Props get passed to the component, State is created and managed within the component,
similar to function parameters similar to a variable declared within the function

Props are used to pass data and event State is used to store the component's data that
handlers down to the child components changes over time

Props are immutable. A component


State should be immutable
cannot change the props

7. State should be minimal

We need the state to make the applications interactive.

To build the application correctly, you first need to think of the minimal set of the state that the
application needs.

Let's take an example application, Projects


Think of all the pieces of data in the Projects Application. We have:

The original list of projects

The active tab item

o The text decoration of the text - Underline

o The color of the text

The filtered list of projects

Let's go through each one and figure out which one is state. Ask three questions about each piece of
data:

Is it passed in from a parent via props? If so, it probably isn't state.

Does it remain unchanged over time? If so, it probably isn't state.

Can it be computed based on any other state or props in the component? If so, it isn't state.

Let's figure out which one is state in our application:

Is
Data Reason
State?
Is
Data Reason
State?

The original list of


No It is passed as props
projects

It changes over time and can't be


The active tab item Yes
computed from anything

It can be computed by combining the


The filtered list of
No original list of projects with the active
projects
tab item

The text decoration of It can be derived from the active tab


No
the text - Underline item

The The color of the It can be derived from the active tab
No
text item

So finally, the state is:

The active tab item

state = {

activeTabId: tabsList[0].tabId,

8. Keys

Keys help React identify which items have been changed, added, or removed.

Keys should be given to the elements inside the array to give a stable identity.

Example:

const usersList = [

uniqueNo: 1,

name: "Rahul",

},

{
uniqueNo: 2,

name: "Praneetha",

},

uniqueNo: 3,

name: "Varakumar",

},

const listItems = usersList.map((user) => (

<li key={user.uniqueNo}>{user.name}</li>

))

8.1 Keys in Lists

When the state of a component changes, React updates the virtual DOM tree. Once the
virtual DOM has been updated, React then compares the new virtual DOM with the current
virtual DOM.
Once React knows which virtual DOM objects have changed, then React updates only those
objects, in the HTML DOM.
React compares the virtual DOMs if there is a change in the node, node type, or the
attributes passed to the node. But there is a problematic case by only looking at the node or
it's attributes. i.e. Lists.
Lists will have the same node types and attributes. Hence the list items can't be uniquely
identified if they have been changed, added, or removed

Example-1:
When a new list item is added to the end of the list,

React creates a new virtual DOM with the three list items.
React compares the first two list items in the current virtual DOM and the new virtual DOM.
Since the two list items in both the previous and current virtual DOMs are matched, React
creates only the last list item at the end in the HTML DOM.

Example-2:

When a new list item is added to the start of the list,

React creates a new virtual DOM with the three list items.

React compares the first list item in the current virtual DOM and the new virtual DOM.

Since the first list item in both the previous and current virtual DOMs is different, React
treats as the whole list is changed in the current virtual DOM.

React creates all the three list items in the HTML DOM.

So, React will recreate every element, instead of reusing the two elements that remained the same
between the previous and current virtual DOMs. It leads to bad performance.

That's where keys are important. Using keys, every item in a list will have a unique identifier (ID).
So, React can easily detect what needs to be changed or not, re-rendering only the ones with
changes.
Third-Party Packages | Cheat Sheet
1. Third-Party Packages

A Third-Party Package is a reusable code developed to perform a specific functionality

1.1 Advantages

Easy integration

Saves Time

More productivity with fewer lines of code

Better Error Handling

More Customisation Options ... many more.

We have used many third-party packages like React Router, React Loader, React Icons, JWT, etc.

Node Package Manager contains Third-Party Packages for React JS, Node JS, Angular JS, and
many more libraries and frameworks. To know more about npm you can refer to this.

1.2 Selecting a Third-Party Package

1.2.1 Things to Consider

Users Satisfaction

Popularity (number of stars)

Maintenance

Documentation

Number of unresolved issues

Compare the packages in the above categories and pick one for the application.

2. Third-Party Package - react-player

NPM contains a react-player, a third-party package that provides a React component for playing a
variety of URLs, including file paths, YouTube, Facebook, etc.

Installation Command: npm install react-player

2.1 React Player Props

We can provide different props to ReactPlayer. Below are some of the most commonly used props.
Default
Prop Description
Value

playing Set to true or false to pause or play the media false

controls Set to true to display native player controls. false

Set to true to show the video thumbnail, which loads the full player
light false
on click. Pass in an image URL to override the preview image

width Set the width of the player 640px

height Set the height of the player 360px

className Add the custom styles to ReactPlayer -

Example:

File: src/App.js

import VideoPlayer from './components/VideoPlayer'

import './App.css'

const App = () => <VideoPlayer />

export default App

File: src/components/VideoPlayer/index.js

import ReactPlayer from 'react-player'

import './index.css'

const videoURL = 'https://youtu.be/YE7VzlLtp-4'

const VideoPlayer = () => (

<div className="video-container">

<h1 className="heading">Video Player</h1>

<div className="responsive-container">

<ReactPlayer url={videoURL} />


</div>

</div>

export default VideoPlayer

ReactPlayer Supports different types of URLs.

2.1.1 controls Prop

File: src/components/VideoPlayer/index.js

const VideoPlayer = () => (

<div className="video-container">

<h1 className="heading">Video Player</h1>

<div className="responsive-container">

<ReactPlayer url={videoURL} controls />

</div>

</div>

export default VideoPlayer

2.1.2 playing Prop

File: src/components/VideoPlayer/index.js

import {Component} from 'react'

import ReactPlayer from 'react-player'

import './index.css'

const videoURL = 'https://youtu.be/YE7VzlLtp-4'

class VideoPlayer extends Component {

state = {

isPlaying: false,
}

onClickPlay = () => {

this.setState(prevState => ({isPlaying: !prevState.isPlaying}))

render() {

const {isPlaying} = this.state

const btnText = isPlaying ? 'Pause' : 'Play'

return (

<div className="video-container">

<h1 className="heading">Video Player</h1>

<div className="responsive-container">

<ReactPlayer url={videoURL} playing={isPlaying} />

</div>

<button type="button" className="button" onClick={this.onClickPlay}>

{btnText}

</button>

</div>

export default VideoPlayer

Reference

To know more about react-player, you can refer to this.

1. Third-Party Package recharts

NPM contains recharts, a third-party package to display charts in your application.

It supports different types of charts like:

Bar Chart
Pie Chart

Area Chart

Composed Chart, etc.

It supports different types of visualization methods like:

Cartesian:

Area

Bar

Line, etc.

Polar:

Pie

Radar

Radial Bar

Installation Command: npm install recharts


1.1 Advantages

Responsive

Built for React, from scratch

Customizable

2. Bar Chart

The BarChart Component represents the container of the Bar Chart.

Example:
import {

BarChart,

Bar,

XAxis,

YAxis,

Legend,

ResponsiveContainer,
} from "recharts"

const data = [

group_name: "Group A",

boys: 200,

girls: 400,

},

group_name: "Group B",

boys: 3000,

girls: 500,

},

group_name: "Group C",

boys: 1000,

girls: 1500,

},

group_name: "Group D",

boys: 700,

girls: 1200,

},

const App = () => {

const DataFormatter = (number) => {

if (number > 1000) {

return `${(number / 1000).toString()}k`


}

return number.toString()

return (

<ResponsiveContainer width="100%" height={500}>

<BarChart

data={data}

margin={{

top: 5,

}}

>

<XAxis

dataKey="group_name"

tick={{

stroke: "gray",

strokeWidth: 1,

}}

/>

<YAxis

tickFormatter={DataFormatter}

tick={{

stroke: "gray",

strokeWidth: 0,

}}

/>

<Legend

wrapperStyle={{
padding: 30,

}}

/>

<Bar dataKey="boys" name="Boys" fill="#1f77b4" barSize="20%" />

<Bar dataKey="girls" name="Girls" fill="#fd7f0e" barSize="20%" />

</BarChart>

</ResponsiveContainer>

export default App

Output:

3. Components in Bar Chart

The recharts supports different Components for the Bar Chart. Below are some of the most
commonly used Components.

3.1 ResponsiveContainer

It is a container Component to make charts adapt to the size of the parent container.

Props:

We can provide different props to the ReactJS ResponsiveContainer Component. Below are
some of the most commonly used props.
Prop Default Value

width '100%' (value can be percentage string or number)

height '100%' (value can be percentage string or number)

Note:

One of the props width and height should be a percentage string in the ResponsiveContainer
Component.

3.2 XAxis

The XAxis Component represents the X-Axis of a Chart.

Props:

We can provide different props to the ReactJS XAxis Component. Below are some of the most
commonly used props.

Prop Description Default Value

The key of the object


dataKey in data that we want to No default value (value can be string or number)
display it's value on the
axis

No default value. If false - No ticks will be drawn, object


- Configuration of ticks, React element - Custom react
tick Represents a tick
element for drawing ticks (value can be boolean, object
or React element)

The formatter function of


tickFormatter No default value (Function)
tick

Example - tickFormatter:

If we want to show the thousands in the form of k on the tick, the formatter function would be:

const DataFormatter = (number) => {

if (number > 1000) {

return `${(number / 1000).toString()}k`

}
return number.toString()

3.3 YAxis

The YAxis Component represents the Y-Axis of a Chart.

The Props of the YAxis Component are similar to the XAxis Component.

3.4 Legend

The Legend Component represents the legend of a Chart.

By default, the content of the legend is generated by the name of Line, Bar, Area, etc. If no name
has been set, the prop dataKey is used to generate the content of the legend.

Props:
We can provide different props to the ReactJS Legend Component. Below are some of the most
commonly used props.

Prop Description Default Value

The type of icon in the No default value (value can be 'line', 'plainline', 'square',
iconType
legend item 'rect', 'circle', 'cross', 'diamond','star', 'triangle', or 'wye')

layout The layout of legend items 'horizontal' (value can be 'horizontal' or 'vertical')

The alignment of legend


verticalAlign 'middle' (value can be 'top', 'middle', or 'bottom')
items in vertical direction

The alignment of legend


align 'center' (value can be 'left', 'center', or 'right')
items in horizontal direction

The style of the legend


wrapperStyle No default value (value can be React Inline styles)
container

3.5 Bar

The Bar Component represents a bar in the Chart.

Props:

We can provide different props to the ReactJS Bar Component. Below are some of the most
commonly used props
Description Default Value
Prop

dataKey The key of the object in data that we want to No default value (value can be string or
display it's value number)

No default value (value can be string or


name The name of the bar
number)

(value can be given color in hexCode or


Fill The color to fill the rectangle in a bar
string format)

barSize The width or height of the bar No default value (value can be number)

Note:

The value of the prop name is used in tooltip and legend to represent a bar/pie. If no value was set,
the value of dataKey will be used alternatively.

4. PieChart

The PieChart Component represents the container of the Pie Chart.

Example:

import { PieChart, Pie, Legend, Cell, ResponsiveContainer } from "recharts"

const data = [

count: 809680,

language: "Telugu",

},

count: 4555697,

language: "Hindi",

},

{
count: 12345657,

language: "English",

},

const App = () => {

return (

<ResponsiveContainer width="100%" height={300}>

<PieChart>

<Pie

cx="70%"

cy="40%"

data={data}

startAngle={0}

endAngle={360}

innerRadius="40%"

outerRadius="70%"

dataKey="count"

>

<Cell name="Telugu" fill="#fecba6" />

<Cell name="Hindi" fill="#b3d23f" />

<Cell name="English" fill="#a44c9e" />

</Pie>

<Legend

iconType="circle"

layout="vertical"

verticalAlign="middle"

align="right"
/>

</PieChart>

</ResponsiveContainer>

export default App

Output:

5. Components in Pie Chart

The recharts supports different Components for the Bar Chart. Below are some of the most
commonly used Components.

5.1 Pie

The Pie Component represents a pie in the Chart.

Props:

We can provide different props to the ReactJS Pie Component. Below are some of the most
commonly used props.

Prop Description Default Value

'50%'. If set a percentage, the final value is


The x-axis coordinate of a obtained by multiplying the percentage of
cx
center point container width (value can be percentage string
or number)
Prop Description Default Value

'50%'. If set a percentage, the final value is


The y-axis coordinate of a obtained by multiplying the percentage of
cy
center point container height (value can be percentage string
or number)

The source data in which each


data No default value (value can be Array)
element is an object

The start angle of the first


startAngle 0 (value can be number)
sector

The end angle of the last


endAngle sector, which should be 360 (value can be number)
unequal to startAngle

The inner radius of all the


innerRadius 0 (value can be percentage or number)
sectors

The outer radius of all the


OuterRadius 0 (value can be percentage or number)
sectors

The key of the object


dataKey in data that we want to No default value
display it's value on the sector

Note

If a percentage is set to the props innerRadius or outerRadius, the final value is obtained by
multiplying the percentage of maxRadius which is calculated by the width, height, cx, and cy.

5.2 Cell

The Cell Component represents the cell of a Chart.

It can be wrapped by a Pie, Bar, or RadialBar Components to specify the attributes of each child.

Props:

We can provide different props to the ReactJS Cell Component. Below are some of the most
commonly used props.

Prop Description Default Value

No default value (can be a string. This value can be taken as the content
Name The name of the cell
of the legend)
Prop Description Default Value

The color to fill the


Fill (value can be any color in hexCode or string format)
cell

Note

The ResponsiveContainer and Legend Components in Pie Chart are similar to the Components in Bar
Chart.
React Context | Cheat Sheet
1. Prop Drilling

Props are passed from one Component to another Component that does not need the data but only
helps in passing it through the tree is called Prop Drilling.

2. React Context

Context is a mechanism that provides different Components and allows us to pass data without
doing prop drilling.

2.1 Creating Context

Syntax: React.createContext(INITIAL_VALUE)
It returns an object with different properties to update and access values from the context.

2.2 Context Properties

The Context object provides two properties.

1. Consumer

2. Provider

2.3 How to Access the Value?

We can access the value in the Context using Consumer Component provided by the Context Object.
3. Consumer Component

Syntax:
<ContextObject.Consumer>

{/*callback function*/}

</ContextObject.Consumer>

We access the Consumer component using dot notation from the context object.
We will give a callback function as children for Consumer Component

3.1 Understanding Syntax

The callback function receives the current context value as an argument and returns a component or
a JSX element.

1. Provider

Provider Component updates the value of Context.


When the provider updates context, all the nested consumers of that provider will be re-
rendered.
Updated context value can only be accessed by the consumers nested within the provider.

Syntax:

<ContextObject.Provider value={/* some value */}>

...

<ContextObject.Provider/>
To update context value, we have to pass it as a prop to the Provider component.

2. Context Flow For Windows App

Best Practice

The context value should have the data which the consumers need.

It should also contain the required methods to update that data.

1. Context

Context can also be used:

When data has to be available between different Routes.


When data has to be available for more number of Components

2. Using Context in methods

We can add consumer or provider in the class method when it returns JSX.
In the below code snippet, we have used Consumer Component in
renderProductDetailsView because this method is returning JSX
Styled Components | Cheat Sheet
1. Styling React Components

React Components can be styled in different ways:

Using CSS

CSS-in-JS

SASS & SCSS

o many more...

1.1 Using CSS

Writing CSS in external CSS files for each component and passing class name as a value to
the className attribute.

File: src/App.js

import "./App.css";

const App = () => <h1 className="heading">Hello World</h1>;

export default App;

File: src/App.css

.heading {

color: #0070c1;

font-family: 'Roboto';

1.2 CSS-in-JS

CSS-in-JS is a styling technique where JavaScript is used to style React Components. It can be
implemented using the below third party packages.

Styled Components

Emotion

Radium many more...


2. Styled Components

Styled Components are one of the new ways to use CSS in modern JavaScript. Components
are used to reuse code, similarly Styled Components are used to reuse styles.

2.1 Installation

npm install styled-components

2.2 Syntax

const StyledComponentName = styled.tagName`

property1: value1;

property2: value2;

...

`;

Within the template literals (), we define the styles.

Note
StyledComponentName should always start with a Capital letter.

2.3 Importing styled

In general, styled components are placed inside the styledComponents.js file.

File: src/styledComponents.js

import styled from "styled-components";

styled is an internal utility method that transforms the styling from JavaScript into actual CSS

2.4 Creating and Exporting Styled Component

File: src/styledComponents.js

import styled from "styled-components";

export const Heading = styled.h1`

color: #0070c1;

font-family: "Roboto";

`;
2.5 Importing and Rendering Styled Component

File: src/App.js

import "./App.css";

import { Heading } from "./styledComponents";

const App = () => <Heading>Hello World</Heading>;

export default App;

2.6 Adapting based on props

With styled components we can re-use the styles created.

<StyledComponent propName="propValue">...</StyledComponent>

Syntax:
const StyledComponentName = styled.tagName`

property1 : value1;

property2: ${props => /* access prop value */ };

...

Example:

File: src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton type="button" color="#ffffff" bgColor="#0070c1">Click</CustomButton>

<CustomButton type="button" color="#0070c1" bgColor="#ffffff">Click</CustomButton>

</>

);

export default App;


File: src/styledComponents.js

import styled from "styled-components";

export const CustomButton = styled.button`

padding: 10px;

margin-right: 20px;

font-size: 15px;

color: ${(props) => props.color};

border-radius: 4px;

border: 2px solid #0070c1;

background-color: ${(props) => props.bgColor};

`;

Value passed as prop can be accessed as props.propName.


2.7 Modularity of Code

Example:

File: src/App.js

<CustomButton type="button" outline={false}>Click</CustomButton>

The color and bgColor are the part of styling, instead of passing them as props, we can passthe type
of button to handle styles in styled components.

2.8 Conditional Styling using Props

Condition ? Expression If True : Expression If False;

const StyledComponentName = styled.tagName`

property1 : value1;

property2: ${(props) => (props.name === someValue ? value2 : value3)};

...

`;
Example:

File: src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton type="button" outline={false}>Click</CustomButton>

<CustomButton type="button" outline={true}>Click</CustomButton>

</>

);

export default App;

File: src/styledComponents.js

import styled from "styled-components";

export const CustomButton = styled.button`

padding: 10px;

margin-right: 20px;

font-size: 15px;

color: ${(props) => (props.outline ? "#0070c1" : "#ffffff")};

border-radius: 4px;

border: 2px solid #0070c1;

background-color: ${(props) => (props.outline ? "#ffffff" : "#0070c1")};

`;

3.Advantages of Styled Components

3.1 Unique Class Names

Styled Components generate a unique class name(s) for your styles.


Example:

3.2 Elimination of dead styles

code.

3.3 Dynamic Styling

a white background, and the other navy blue.

We do not have to create two styled-components for them. We can adapt their
styling based on their props

File:src/styledComponents.js

import styled from "styled-components";

export const CustomButton = styled.button`

padding: 10px;

margin-right: 20px;

font-size: 15px;

color: ${(props) => (props.outline ? "#0070c1" : "#ffffff")};

border-radius: 4px;

border: 2px solid #0070c1;

background-color: ${(props) => (props.outline ? "#ffffff" : "#0070c1")};

`;
File:src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton type="button" outline={false}>Click</CustomButton>

<CustomButton type="button" outline={true}>Click</CustomButton>

</>

);

export default App;

3.4 Can differentiate between the types of props they receive

File:src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton outline={false}>Click</CustomButton>

<CustomButton outline={true}>Click</CustomButton>

</>

);

export default App;

File:src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (


<>

<CustomButton type="button" outline={false}>Click</CustomButton>

<CustomButton type="submit" onClick={() => alert("clicked")} outline={true}


>Click</CustomButton>

</>;

);

export default App;

Styled components can differentiate between the types of props they receive. They know
that type is an HTML attribute, so they render <button type="button">Click</button>,
while using the outline prop in their own processing. Notice how we attached an event
handler, too?

3.5 Easier Debugging

babel-plugin-styled-components plugin adds support for a nicer debugging experience.

This option enhances the attached CSS class name on each component with richer output to
help identify your components in the DOM without React DevTools. In your page source
you'll see: <button type="button" class="CustomButton-asdfxxx asdfxx" /> instead of just
<button type="button" class="asdfxxx" />.

It also allows you to see the component's displayName in React DevTools. For example,
consider writing a styled component that renders a button element, called CustomButton. It
will normally show up in DevTools as styled.button, but with the displayName option
enabled, it has the name you gave it CustomButton.
This makes it easier to find your components and to figure out where they live in your app.

For more info, you can go through this link here.

Note

In order to configure create-react-app with the babel-plugin-styled-components, we


have to use craco - Create React App Configuration Override is an easy and
comprehensible configuration layer for create-react-app.

need to install craco with npm, and then create a craco.config.js at the root of
our application, with the content:

module.exports = {

babel: {

plugins: [

"babel-plugin-styled-components",

fileName: false,

},

],

],

},

};

It is already configured.
3.6 Global Styling

We will write global styles in the styledComponentsjs file. Inside the GlobalStyle variable is
where we define all global styles.

We will import GlobalStyle component and place it at the top of React tree. In many react
App.js file.

createGlobalStyle is a helper function to generate a special StyledComponent that handles


global styles.

Normally, styled-components are automatically scoped to a local CSS class and therefore
isolated from other components. In the case of createGlobalStyle, this limitation is
removed.

Example:

File: src/styledComponents.js

import { createGlobalStyle } from "styled-components";

export const GlobalStyle = createGlobalStyle`

body {

margin: 0;

font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",

"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",

sans-serif;

-webkit-font-smoothing: antialiased;

-moz-osx-font-smoothing: grayscale;

`;

Example:

File: src/styledComponents.js

import { createGlobalStyle } from "styled-components";

export const GlobalStyle = createGlobalStyle`


body {

margin: 0;

font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",

"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",

sans-serif;

-webkit-font-smoothing: antialiased;

-moz-osx-font-smoothing: grayscale;

`;

File: src/App.js

import { CustomButton } from "./styledComponents";

import { GlobalStyle } from "./styledComponents";

const App = () => (

<>

<GlobalStyle />

<CustomButton type="button">Click</CustomButton>

<CustomButton type="button" outline>Click</CustomButton>

</>

);

export default App;

4. Extending Styles

Frequently you might want to use a component, but change it slightly for a single
case. Now, you could pass in a function and change them based on some props, but
that's quite a lot of effort for overriding the styles once.

To easily make a new component that inherits the styling of another, just wrap it in
the styled(). Here we use the CustomButton and create a special one, extending it
with some color-related styling.
import styled from "styled-components";

export const CustomButton = styled.button`

padding: 10px;

margin-right: 20px;

font-size: 15px;

color: #ffffff;

border-radius: 4px;

border: 2px solid #0070c1;

background-color: #0070c1;

`;

Now we need to create another StyledComponent with similar properties


of CustomButton except color and border-color property.

import styled from "styled-components";

export const OutlineButton = styled(CustomButton)`

color: #0070c1;

background-color: #ffffff;

font-family: "Open sans";

`;

spread operator works.


Note
You will get a HTML button element rendered for OutlineButton.

5. The "as" prop

You can pass the as prop to your styled component with the value of your preferred
element.

If you want to keep all the styling you've applied to a component but just switch out what's
being ultimately rendered (be it a different HTML tag or a different custom component), you
can use the "as" prop to do this at runtime.

Example:

File:src/App.js

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton outline={false}>Click</CustomButton>

<CustomButton as="a" href="#" outline={true}>Click</CustomButton>

</>

);

export default App;

File:src/styledComponents.js

import styled from "styled-components";

export const CustomButton = styled.button`

padding: 10px;

margin-right: 20px;

font-size: 15px;

color: ${(props) => (props.outline ? "#0070c1" : "#ffffff")};

border-radius: 4px;
border: 2px solid #0070c1;

background-color: ${(props) => (props.outline ? "#ffffff" : "#0070c1")};

`;

Consider the above code snippet, here the OutlineButton styled component is
rendered as a button element, but you would prefer an anchor to a button
for OutlineButton, you can pass the as a prop to your styled component with the
value of your preferred element.

This sort of thing is very useful in use cases like a navigation bar where some of the items
should be links and some just buttons, but all be styled the same way.

6. Boolean Attribute

The Presence of boolean attribute is taken as true no need to specify the value again.

The absence of boolean attribute is taken as false.

import "./App.css";

import { CustomButton } from "./styledComponents";

const App = () => (

<>

<CustomButton type="button">Click</CustomButton>

<CustomButton type="button" outline>Click</CustomButton>

</>

);

export default App;


React Chrono | Reading Material

1. Third-Party Package react-chrono

NPM contains a react-chrono, a third-party package to display the timeline in your application.

It provides a React component Chrono to build a timeline that displays events chronologically

Installation Command: npm install react-chrono

1.1 Advantages

Can render the timelines in three different modes (horizontal, vertical, and tree).

Can autoplay the timeline with slideshow mode.

Can navigate the timeline via keyboard.

2. Chrono Props

We can provide different props to the ReactJS Chrono component. Below are some of the most
commonly used props

Prop Description Default Value

Sets the mode of the 'HORIZONTAL' (value can be 'HORIZONTAL', 'VERTICAL' or


mode
component 'VERTICAL_ALTERNATING')

Collection of Timeline
items []
Item Model

theme Customises the colors No default value

2.1 mode

Example: <Chrono mode="VERTICAL" />

2.2 items

The items prop is used to build the timeline. It is a collection of the Timeline Item Model.

Timeline Item Model is an object consist of the given properties:


Description Type
Name

title title of the timeline item String

cardTitle title of the timeline card String

cardSubtitle text of the timeline card String

cardDetailedText detailed text of the timeline card String or String[]

media media object to set image or video Object

Example:
CSS:

.chrono-container {

width: 500px;

height: 400px;

JSX:

import {Chrono} from 'react-chrono'

const items = [

title: 'May 1940',

cardTitle: 'Dunkirk',

cardSubtitle: 'Men of the British Expeditionary Force.',

cardDetailedText:

'On 10 May 1940, Hitler began his long-awaited offensive in the west by invading neutral Holland
and attacking northern France.',

},

]
const App = () => (

<div className="chrono-container">

<Chrono items={items} />

</div>

export default App

Output:

A single timeline item is created with the values of the Timeline Item Model in the items prop.

Warning
If any property misses in the Timeline Item Model, the respective value won't be
displayed in the timeline item.

Note
The Chrono Component should be wrapped in a container that has a width and height.
2.3 theme

The colors can be customized with the theme prop.

Example
<Chrono

theme={{

primary: "red",

secondary: "blue",

cardBgColor: "yellow",

cardForeColor: "violet",

titleColor: "red",

}}

/>

3. Rendering Custom Content

The custom content can be inserted by just passing the elements between the Chrono tags.

Example
The below example will create two timeline items.

CSS:

.chrono-container {

width: 400px;

height: 600px;

.image {

width: 200px;

height: 200px;

}
JSX:

import {Chrono} from 'react-chrono'

const App = () => (

<div className="chrono-container">

<Chrono mode="VERTICAL">

<div>

<img

src="https://assets.ccbp.in/frontend/react-js/csk-logo-img.png"

className="image"

alt="chennai-super-kings"

/>

</div>

<div>

<h1>Mumbai Indians</h1>

<p>IPL Team winner for the year 2019 is Mumbai Indians.</p>

</div>

</Chrono>

</div>

export default App

Output:

Each HTML div element is automatically converted into a timeline item and inserted into the
timeline card
Note
The items prop is optional and custom rendering is supported on all three modes.

Example
The below example will set the title for the custom contents

CSS:

.chrono-container {

width: 400px;

height: 600px;

}
.image {

width: 200px;

height: 200px;

JSX:

import {Chrono} from 'react-chrono'

const items = [{title: '2018'}, {title: '2019'}]

const App = () => (

<div className="chrono-container">

<Chrono mode="VERTICAL" items={items}>

<img

src="https://assets.ccbp.in/frontend/react-js/csk-logo-img.png"

className="image"

alt="chennai-super-kings"

/>

<div>

<h1>Mumbai Indians</h1>

<p>IPL Team winner for the year 2019 is Mumbai Indians.</p>

</div>

</Chrono>

</div>

export default App

Output:
4. Reference To know more about the react-chrono, you can refer to this.
React Slick | Reading Material
1. Third-Party Package - react-slick

NPM contains a react-slick, a third-party package that provides a React component Slider to add a
carousel to your application.

Installation Command: npm install react-slick

Also, install slick-carousel for CSS and font

npm install slick-carousel

1.1 Advantages

Easy to use

Highly customizable

More performant

2. Slider Props

We can provide different props to the Slider component. Below are the most commonly used props.

Prop Description Default Value

slidesToShow Specifies the number of slides to show in one frame 1

dots If set to false, no dots will display under the carousel true

slidesToScroll Specifies the number of slides to scroll at once 1

dotsClass CSS class for styling dots "slick-dots"

Example:

File: src/components/ReactSlick/index.js

import Slider from 'react-slick'


import 'slick-carousel/slick/slick.css'

import 'slick-carousel/slick/slick-theme.css'

import './index.css'

const ReactSlick = () => {

const settings = {

dots: true,

slidesToShow: 1,

slidesToScroll: 1,

return (

<div className="slider-container">

<Slider {...settings}>

<div>

<h3>1</h3>

</div>

<div>

<h3>2</h3>

</div>

<div>

<h3>3</h3>

</div>

<div>
<h3>4</h3>

</div>

</Slider>

</div>

export default ReactSlick

File: src/components/ReactSlick/index.css

.slider-container {

background-color: #419be0;

padding: 40px;

File: src/App.js

import ReactSlick from './components/ReactSlick'

const App = () => {

return <ReactSlick />

export default App

Reference : To know more about the react-slick, you can refer to this
React Popup | Reading Material
1. Third-Party Package reactjs-popup

NPM contains a reactjs-popup, a third-party package to display popup in your application.

It provides a React component that helps you create simple and complex Modals, Tooltips, and
Menus for your application.

Installation Command: npm install reactjs-popup

1.1 Advantages

ReactJS provides Modal, Tooltip, and Menu

Provides Support for controlled Modals & Tooltips

2. ReactJS Popup Props

We can provide different props to the ReactJS Popup component. Below are some of the most
commonly used props.

Prop Description Default Value

JSX
trigger Represents the element to be rendered in-place where the Popup is defined
element

When set to true, Popup content will be displayed as a modal on the trigger of
modal false
Popup. If not tooltip will be displayed

Defines the position of the tooltip. It can be one of 'top left', 'top right', bottom
position
'bottom right', 'bottom left' center

open Defines the state of Popup. Whether it is opened or not false

overlayStyle Custom overlay style object

2.1 trigger Prop

File: src/components/ReactPopup/index.js

import Popup from 'reactjs-popup'


import 'reactjs-popup/dist/index.css'

import './index.css'

const ReactPopUp = () => (

<div className="popup-container">

<Popup

trigger={

<button className="trigger-button" type="button">

Trigger

</button>

>

<div>

<p>React is a popular and widely used programming language</p>

</div>

</Popup>

</div>

export default ReactPopUp

File: src/components/ReactPopup/index.css

.trigger-button {

font-size: 16px;

font-weight: 400;
font-family: 'Roboto';

color: white;

padding: 8px 15px 8px 15px;

margin: 8px;

background-color: #7c69e9;

border: none;

border-radius: 4px;

outline: none;

.popup-container {

display: flex;

align-items: center;

justify-content: center;

height: 100vh;

File: src/App.js

import ReactPopup from './components/ReactPopup'

const App = () => {

return <ReactPopup />

export default App

Note
The value of the trigger prop should be a JSX element.
2.2 modal Prop

File: src/components/ReactPopup/index.js

const ReactPopUp = () => (

<div className="popup-container">

<Popup

modal

trigger={

<button type="button" className="trigger-button">

Trigger

</button>

>

<p>React is a popular and widely used programming language</p>

</Popup>

</div>

export default ReactPopUp

2.3 modal Prop with close button

File: src/components/ReactPopup/index.js

const ReactPopUp = () => (

<div className="popup-container">

<Popup
modal

trigger={

<button type="button" className="trigger-button">

Trigger

</button>

>

{close => (

<>

<div>

<p>React is a popular and widely used programming language</p>

</div>

<button

type="button"

className="trigger-button"

onClick={() => close()}

>

Close

</button>

</>

)}

</Popup>
</div>

export default ReactPopUp

2.4 position Prop

File: src/components/ReactPopup/index.js

const ReactPopUp = () => (

<div className="popup-container">

<Popup

trigger={

<button type="button" className="trigger-button">

Trigger

</button>

position="bottom left"

>

<p>React is a popular and widely used programming language</p>

</Popup>
</div>

)export default ReactPopUp

2.5 overlayStyle Prop

File: src/components/ReactPopup/index.js
const overlayStyles = {

backgroundColor: '#ffff',

const ReactPopUp = () => (

<div className="popup-container">

<Popup

modal

trigger={

<button type="button" className="trigger-button">

Trigger

</button>

overlayStyle={overlayStyles}

>
<p>React is a popular and widely used programming language</p>

</Popup>

</div>

export default ReactPopUp

Reference

To know more about the reactjs-popup, you can refer to this.

You might also like