Reactfile
Reactfile
1. React JS
React JS is an open-source JavaScript library used to build user interfaces. It was developed by
Facebook.
Performant websites
Open Source
Reusable code
Easy to Learn
Large Community
Developer Toolset
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">
element.classList.add("greeting");
rootElement.appendChild(element);
</script>
</body>
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.
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.
<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.
Example:
<script type="module">
Note:
The type attribute value of the HTML script element should be module to run React JS.
3.3 ReactDOM.render()
Example:
<body>
<div id="root"></div>
<script type="module">
ReactDOM.render(element, document.getElementById("root"));
</script>
</body>
4. JSX
React JS introduced a new HTML like syntax named JSX to create elements.
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.
Example:
<script type="text/babel">
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.
HTML JSX
class className
for htmlFor
We can embed the variables and expressions using the flower brackets {}.
<body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(element, document.getElementById("root"));
</script>
</body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(element, document.getElementById("root"));
</script>
</body>
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>
</div>
);
ReactDOM.render(element, document.getElementById("root"));
</script>
</body>
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">
</script>
We can call the function with self-closing tags as shown above <Welcome />
We can pass props to any component as we declare attributes for any HTML element.
Example:
ReactDOM.render(
<Welcome name="Rahul" greeting="Hello" />,
document.getElementById("root")
);
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")
);
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")
);
Example:
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.
2.1 create-react-app
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
You can view the application in the URL http://localhost:3000 in your browser.
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
Example:
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:
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.
They are:
Functional Components
Class Components
These are JavaScript functions that take props as a parameter if necessary and return react element
(JSX).
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";
render() {
return JSX;
}
Use this.props in the render() body to access the props in a class component.
render() {
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:
Example:
HTML JSX
onclick onClick
onblur onBlur
onchange onChange
2. With JSX, you pass a function as the event handler rather than a string.
handleClick = () => {
console.log("clicked")
}
render() {
handleClick = () => {
console.log("clicked")
render() {
In the above function, the handleClick is passed as a reference. So, the function is not being called
every time the component renders.
To not change the context of this, we have to pass an arrow function to the event.
Example1:
handleClick() {
console.log(this) // undefined
render() {
Example2:
class MyComponent extends Component {
handleClick = () => {
render() {
3. State
The state is a JS object in which we store the component's data that changes over time.
Intialising State:
state = { count: 0 }
render() {
We can update the state by using setState(). We can provide function/object as an argument to set
the state.
onIncrement = () => {
this.setState((prevState) =>
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:
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
import './App.css'
renderAuthButton = () => {
return <button>Logout</button>
return <button>Login</button>
render() {
return (
<div className="container">
{this.renderAuthButton()}
</div>
import './App.css'
let authButton
if (isLoggedIn) {
authButton = <button>Logout</button>
} else {
authButton = <button>Login</button>
return (
<div className="container">
<h1>React JS</h1>
{authButton}
</div>
import './App.css'
render() {
return (
<div className="container">
</div>
)
import './App.css'
render() {
return (
<div className="container">
</div>
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
return (
<h1 className="message">
{greeting}, {name}
</h1>
);
};
Welcome.defaultProps = {
name: "Rahul",
greeting: "Hello"
};
File: src/App.js
import { Component } from "react";
render() {
return (
<div className="container">
<Welcome greeting="Hello" />
</div>
);
Note
While accessing the props, the correct prop name should be given.
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}
);
});
It is used while updating the state to a value, which is computed based on the previous state.
Controlled Input
Uncontrolled 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'
state = {
searchInput: '',
this.setState({
searchInput: event.target.value,
})
render() {
return (
<input
type="text"
onChange={this.onChangeSearchInput}
value={searchInput}
/>
}
export default App
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.
1.1 Authentication
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.
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.
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");
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
2. Storage Mechanisms
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.
Examples:
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.1 Cookies.set()
Syntax:
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.
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:
...
1.Router Switch
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.
File: src/components/ProtectedRoute/index.js
};
The setState() is asynchronous, it takes an optional callback parameter that can be used to
make updates after the state is changed.
2. React Icons
This below command installs all the react-icons library in your React project
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:
return (
<div>
<BsFilterRight />
<FaFacebookF />
<MdDelete />
</div>
);
};
Debugging is the process of finding & fixing the bugs in the code.
These are the tools provided by the browsers to debug the application loaded in the web browser.
For React Developer Tools, we can install the React Developer Tools Extension for Google Chrome.
The best practice is to create a new array/object from the array/object in the previous state
using the spread operator.
this.setState(prevState => ({
}))
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.
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)
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.
super(props)
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.
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
4.1.1 componentWillUnmount()
The browser downloads these resources when you access them or navigate between
URLs.
On navigating we only get the additional content (Component - HTML, CSS, JS).
Faster Page loading - since they load only necessary Component (HTML, CSS, JS)
resources on subsequent requests.
2. React Router
BrowserRouter
Link
Route
Switch
2.1 BrowserRouter
Syntax: <BrowserRouter>
<Component 1>
<Component 2>
...
</BrowserRouter>
2.2 Link
2.3 Route
The Route component renders specific UI component when path matches current URL.
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>
3. Routing Example
File: src/App.js
import { BrowserRouter, Route, Switch } from "react-router-dom"
...
<BrowserRouter>
<Header />
<Switch>
</Switch>
</BrowserRouter>
File: src/components/Header/index.js
import { Link } from "react-router-dom";
...
...
<ul className="nav-menu">
<li>
<li>
</li>
<li>
</li>
</ul>
...
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
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.
state = { count: 0 }
onIncrement = () => {
render() {
console.log("render() called")
return (
<>
<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
this.setState({
count: 5,
})
Callback Syntax is used while updating the state to a value that is computed based on the previous
state.
Object Syntax:
state = { count: 0 }
onIncrement = () => {
render() {
<>
<button onClick={this.onIncrement}>Increase</button>
</>
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:
state = { count: 0 }
onIncrement = () => {
render() {
return (
<>
</>
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.
File: src/components/Post/index.js
import "./index.css"
<div className="post-container">
<SocialButton>Like</SocialButton>
</div>
File: src/components/SocialButton/index.js
import "./index.css"
<button className="social-button">{props.children}</button>
)
Controlled Input
Uncontrolled Input
If the Input Element value is handled by a React State, then it is called Controlled Input.
Example:
state = {
searchInput: "",
this.setState({
searchInput: event.target.value,
})
render() {
return (
<>
<input
type="text"
onChange={this.onChangeSearchInput}
value={searchInput}
/>
<p>{searchInput}</p>
</>
If the Input Element value is handled by the browser itself, then it is called Uncontrolled Input.
Example:
state = {
searchInput: "",
this.setState({
searchInput: event.target.value,
})
render() {
return (
<>
<p>{searchInput}</p>
</>
6. Props vs State
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
To build the application correctly, you first need to think of the minimal set of the state that the
application needs.
Let's go through each one and figure out which one is state. Ask three questions about each piece of
data:
Can it be computed based on any other state or props in the component? If so, it isn't state.
Is
Data Reason
State?
Is
Data Reason
State?
The The color of the It can be derived from the active tab
No
text 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",
},
<li key={user.uniqueNo}>{user.name}</li>
))
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:
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
1.1 Advantages
Easy integration
Saves Time
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.
Users Satisfaction
Maintenance
Documentation
Compare the packages in the above categories and pick one for the application.
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.
We can provide different props to ReactPlayer. Below are some of the most commonly used props.
Default
Prop Description
Value
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
Example:
File: src/App.js
import './App.css'
File: src/components/VideoPlayer/index.js
import './index.css'
<div className="video-container">
<div className="responsive-container">
</div>
File: src/components/VideoPlayer/index.js
<div className="video-container">
<div className="responsive-container">
</div>
</div>
File: src/components/VideoPlayer/index.js
import './index.css'
state = {
isPlaying: false,
}
onClickPlay = () => {
render() {
return (
<div className="video-container">
<div className="responsive-container">
</div>
{btnText}
</button>
</div>
Reference
Bar Chart
Pie Chart
Area Chart
Cartesian:
Area
Bar
Line, etc.
Polar:
Pie
Radar
Radial Bar
Responsive
Customizable
2. Bar Chart
Example:
import {
BarChart,
Bar,
XAxis,
YAxis,
Legend,
ResponsiveContainer,
} from "recharts"
const data = [
boys: 200,
girls: 400,
},
boys: 3000,
girls: 500,
},
boys: 1000,
girls: 1500,
},
boys: 700,
girls: 1200,
},
return number.toString()
return (
<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,
}}
/>
</BarChart>
</ResponsiveContainer>
Output:
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
Note:
One of the props width and height should be a percentage string in the ResponsiveContainer
Component.
3.2 XAxis
Props:
We can provide different props to the ReactJS XAxis Component. Below are some of the most
commonly used props.
Example - tickFormatter:
If we want to show the thousands in the form of k on the tick, the formatter function would be:
}
return number.toString()
3.3 YAxis
The Props of the YAxis Component are similar to the XAxis Component.
3.4 Legend
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.
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')
3.5 Bar
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)
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
Example:
const data = [
count: 809680,
language: "Telugu",
},
count: 4555697,
language: "Hindi",
},
{
count: 12345657,
language: "English",
},
return (
<PieChart>
<Pie
cx="70%"
cy="40%"
data={data}
startAngle={0}
endAngle={360}
innerRadius="40%"
outerRadius="70%"
dataKey="count"
>
</Pie>
<Legend
iconType="circle"
layout="vertical"
verticalAlign="middle"
align="right"
/>
</PieChart>
</ResponsiveContainer>
Output:
The recharts supports different Components for the Bar Chart. Below are some of the most
commonly used Components.
5.1 Pie
Props:
We can provide different props to the ReactJS Pie Component. Below are some of the most
commonly used props.
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
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.
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
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.
Syntax: React.createContext(INITIAL_VALUE)
It returns an object with different properties to update and access values from the context.
1. Consumer
2. Provider
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
The callback function receives the current context value as an argument and returns a component or
a JSX element.
1. Provider
Syntax:
...
<ContextObject.Provider/>
To update context value, we have to pass it as a prop to the Provider component.
Best Practice
The context value should have the data which the consumers need.
1. Context
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
Using CSS
CSS-in-JS
o many more...
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";
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
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
2.2 Syntax
property1: value1;
property2: value2;
...
`;
Note
StyledComponentName should always start with a Capital letter.
File: src/styledComponents.js
styled is an internal utility method that transforms the styling from JavaScript into actual CSS
File: src/styledComponents.js
color: #0070c1;
font-family: "Roboto";
`;
2.5 Importing and Rendering Styled Component
File: src/App.js
import "./App.css";
<StyledComponent propName="propValue">...</StyledComponent>
Syntax:
const StyledComponentName = styled.tagName`
property1 : value1;
...
Example:
File: src/App.js
import "./App.css";
<>
</>
);
padding: 10px;
margin-right: 20px;
font-size: 15px;
border-radius: 4px;
`;
Example:
File: src/App.js
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.
property1 : value1;
...
`;
Example:
File: src/App.js
import "./App.css";
<>
</>
);
File: src/styledComponents.js
padding: 10px;
margin-right: 20px;
font-size: 15px;
border-radius: 4px;
`;
code.
We do not have to create two styled-components for them. We can adapt their
styling based on their props
File:src/styledComponents.js
padding: 10px;
margin-right: 20px;
font-size: 15px;
border-radius: 4px;
`;
File:src/App.js
import "./App.css";
<>
</>
);
File:src/App.js
import "./App.css";
<>
<CustomButton outline={false}>Click</CustomButton>
<CustomButton outline={true}>Click</CustomButton>
</>
);
File:src/App.js
import "./App.css";
</>;
);
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?
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.
Note
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.
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
body {
margin: 0;
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
`;
Example:
File: src/styledComponents.js
margin: 0;
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
`;
File: src/App.js
<>
<GlobalStyle />
<CustomButton type="button">Click</CustomButton>
</>
);
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";
padding: 10px;
margin-right: 20px;
font-size: 15px;
color: #ffffff;
border-radius: 4px;
background-color: #0070c1;
`;
color: #0070c1;
background-color: #ffffff;
`;
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";
<>
<CustomButton outline={false}>Click</CustomButton>
</>
);
File:src/styledComponents.js
padding: 10px;
margin-right: 20px;
font-size: 15px;
border-radius: 4px;
border: 2px solid #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.
import "./App.css";
<>
<CustomButton type="button">Click</CustomButton>
</>
);
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
1.1 Advantages
Can render the timelines in three different modes (horizontal, vertical, and tree).
2. Chrono Props
We can provide different props to the ReactJS Chrono component. Below are some of the most
commonly used props
Collection of Timeline
items []
Item Model
2.1 mode
2.2 items
The items prop is used to build the timeline. It is a collection of the Timeline Item Model.
Example:
CSS:
.chrono-container {
width: 500px;
height: 400px;
JSX:
const items = [
cardTitle: 'Dunkirk',
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">
</div>
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
Example
<Chrono
theme={{
primary: "red",
secondary: "blue",
cardBgColor: "yellow",
cardForeColor: "violet",
titleColor: "red",
}}
/>
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:
<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>
</div>
</Chrono>
</div>
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:
<div className="chrono-container">
<img
src="https://assets.ccbp.in/frontend/react-js/csk-logo-img.png"
className="image"
alt="chennai-super-kings"
/>
<div>
<h1>Mumbai Indians</h1>
</div>
</Chrono>
</div>
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.
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.
dots If set to false, no dots will display under the carousel true
Example:
File: src/components/ReactSlick/index.js
import 'slick-carousel/slick/slick-theme.css'
import './index.css'
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>
File: src/components/ReactSlick/index.css
.slider-container {
background-color: #419be0;
padding: 40px;
File: src/App.js
Reference : To know more about the react-slick, you can refer to this
React Popup | Reading Material
1. Third-Party Package reactjs-popup
It provides a React component that helps you create simple and complex Modals, Tooltips, and
Menus for your application.
1.1 Advantages
We can provide different props to the ReactJS Popup component. Below are some of the most
commonly used props.
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
File: src/components/ReactPopup/index.js
import './index.css'
<div className="popup-container">
<Popup
trigger={
Trigger
</button>
>
<div>
</div>
</Popup>
</div>
File: src/components/ReactPopup/index.css
.trigger-button {
font-size: 16px;
font-weight: 400;
font-family: 'Roboto';
color: white;
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
Note
The value of the trigger prop should be a JSX element.
2.2 modal Prop
File: src/components/ReactPopup/index.js
<div className="popup-container">
<Popup
modal
trigger={
Trigger
</button>
>
</Popup>
</div>
File: src/components/ReactPopup/index.js
<div className="popup-container">
<Popup
modal
trigger={
Trigger
</button>
>
{close => (
<>
<div>
</div>
<button
type="button"
className="trigger-button"
>
Close
</button>
</>
)}
</Popup>
</div>
File: src/components/ReactPopup/index.js
<div className="popup-container">
<Popup
trigger={
Trigger
</button>
position="bottom left"
>
</Popup>
</div>
File: src/components/ReactPopup/index.js
const overlayStyles = {
backgroundColor: '#ffff',
<div className="popup-container">
<Popup
modal
trigger={
Trigger
</button>
overlayStyle={overlayStyles}
>
<p>React is a popular and widely used programming language</p>
</Popup>
</div>
Reference