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

Harry React CheatSheet

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

Harry React CheatSheet

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

REACT.

JS
CHEATSHEET

REACT HOME

What is ReactJS?
ReactJS is a JavaScript library used to build User Interfaces(UI). It
significantly decreases the code with it's components, states i.e.
hooks, etc.

Creating react app


Open your terminal in the directory you would like to create your
application. Run this command to create a React application
named my-react-app:

npx create-react-app my-react-app

Copy
OR, you can directly make your application without specifying a
name, like this:

npx create-react-app .

Copy
In this case, all files will be kept in the current directory.
Note: When choosing folder name, make sure there are no spaces
or capital letters because of npm naming restrictions.
Once base application is created, if folder specified you just have
to enter the folder. You can use this command to enter:

cd directory-name

Copy
Then just start up the application with this command:

npm start

Copy
and you are good to go!

Hello World

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);

Copy
In this we are just putting <h1> tag in a div with id 'root'. That's it!
In div with id 'root' everything will be rendered. We can also
change it from 'root' to something else, as we are just getting an
element and putting HTML in it.

REACT ES6

What is ES6?
ES6 stands for ECMAScript 6. ECMAScript is a JavaScript standard
intended to ensure a common language across different browsers.
ES6 is the 6th version of ECMAScript.

Why ES6? / Features of ES6 / Upgrades in ES6


React uses ES6 and all of these new features will make your
coding experience in react much much better. You will be able to
do things with much more ease and in very less lines! Features
like:

 Arrow Functions:

const hello = () => {


return "Hello World!";
}

Copy
or

const hello = () => "Hello World!";

Copy

 .map(): .map can be used for alot of things, one of it's use
case is, we can make any number of cards through loop
and just put it in jsx, like this:

const data = ['title1', 'title2', 'title3'];


let cards = data.map((item) => <card>{item}</card>)

Copy

 Destructuring:

Old Way:

const languages = ['JS', 'Python', 'Java'];


const js = languages[0]
const python = languages[1]
const java = languages[2]

Copy
New Way:

const languages = ['JS', 'Python', 'Java'];


const [ js, python, java ] = languages

Copy

 Ternary Operator: With this, you can write if/else


conditions in one line. It's syntax is fairly simple like this:

condition ? <expression if true> : <expression if false>

Copy
Example:

let loading = false;


const data = loading ? <div>Loading...</div> :
<div>Data</div>

Copy

 Spread Operator:

const languages = ['JS', 'Python', 'Java'];


const morelanguages = ['C', 'C++', 'C#']

const allLanguages = [...languages, ...morelanguages]

Copy
Output:

["JS","Python","Java","C","C++","C#"]

Copy
and many more like, classes, modules.

REACT RENDER HTML


React renders HTML to the web page by using a function
called ReactDOM.render().

ReactDOM.render()
This function takes two arguments, HTML content which you want
to show on page and HTML element where you want to put the
HTML content(first argument).
But where will it find that element? It will find it inside "index.html"
located in "public" folder. There you will notice a div with id "root".
That is where all this will be rendered!

ReactDOM.render(<p>Hello</p>,
document.getElementById('root'));

Copy

REACT JSX

What is JSX?
JSX stands for JavaScript XML. It is similar in appearance to HTML,
hence provides a way to easily write HTML in react.

Coding in JSX
Earlier we had to make an HTML element or append it into existing
ones with methods like createElement() / appendChild()

const elem = React.createElement('h1', {}, 'Hello


World!');

Copy
Now we can just do it directly, like this:

const elem = <h1>Hello World!</h1>

Copy
Expressions in JSX
You can write the expression in {}
You can write simple mathematical operations to variable to states
to complicated operations with ternary operators and it will return
the result, like:
Mathematical Operations:

const elem = <h1>React was released in {2010+3}</h1>

Copy
Variables/States:

const name = "CWH"


const elem = <h1>My name is {name}</h1>

Copy
Ternary Operators:

const elem = <h1>Hello {name ? name : 'World'}</h1>

REACT COMPONENT
There are two types of components:

1. Class Based Components


2. Function Based Components

Class Based Components


Before making class based component we need to inherit functions
from React.Component and this can be done with extends, like
this:

class Cat extends React.Component {


render() {
return <h1>Meow</h1>;
}
}

Copy
it also requires a render method which returns HTML.

Function Based Components


In function it's simpler, we just need to return the HTML, like this:

function Cat() {
return <h1>Meow</h1>;
}

Copy
Note: Component's name must start with uppercase letter.

Rendering a Component
We made a component, now we want to render/use it. Syntax for
using a component is:

<ComponentName />

Copy

Components in Files
To have less mess inside main file(with all the components in the
same file) and to resuse components on different pages, we have
to make them separately. So that we can just import them in any
file and use them!
For that we will just make a new file called Cat.js, make class or
function based component there and export default that
class/function! Like this:

function Cat() {
return <h1>Meow</h1>;
}

export default Cat;

Copy
Note: File name must start with uppercase letter.

Props
As mentioned earlier, we can import the same component in
different files and use it, but maybe in different files some changes
in the component is needed. For that, we can use props! Like this:
Component:

function Cat(props) {
return <h1>Meow's color is {props.color}</h1>;
}

Copy
Main file:

<Cat color="purple" />

REACT CLASS

Class Based Components


Before making class based component we need to inherit functions
from React.Component and this can be done with extends, like
this:

class Cat extends React.Component {


render() {
return <h1>Meow</h1>;
}
}

Copy
it also requires a render method which returns HTML.
Note: Component's name must start with uppercase letter.

Component Constructor
Constructor gets called when the component is initiated. This is
where you initiate the component's properties. In React we have
states which update on page without reload. Constructor
properties are kept in state.
We also need to add super() statement, which executes the
parent component's constructor and component gets access to all
the functions of the parent component, like this:

class Cat extends React.Component {


constructor() {
super();
this.state = { color: "orange" };
}
render() {
return <h1>Meow's color is {this.state.color}</h1>;
}
}

REACT PROPS
Props are arguments passed to React components via HTML attributes.
Example:
Component:
function Cat(props) {
return <h1>Meow's color is {props.color}</h1>;
}

Copy
Main file:

<Cat color="purple" />

Copy
Output:

REACT EVENTS
If you have coded even a little bit in javascript, you know the
importance of events.

Events
Every HTML attribute in React is written in camelCase syntax.
Event is also an attribute. Hence, written in camelCase.
As we learnt variables, states, javascript operations are written in
curly braces {}, same is true with React event handlers too! Like
this: onClick={show}

<button onClick={show}>Show</button>

Copy

Arguments in events
We can't pass arguments just like that, it will give syntax error.
First, we need to put the whole function in arrow function, like this:

<button onClick={ ()=>show('true') }>Show</button>

Copy

React Event Object


Event handler can be provided to the function like this:

<button onClick={ (event)=>show('true', event)


}>Show</button>

REACT CONDITION

React Conditional
One of the best thing in React is in React we can conditionally
render elements/components!

&& Operator
This is one of the way to conditionally render:

function App() {
const loading = true;

return (
<div className="App">
{loading && <LoadingGif />}
{!loading && <Content />}
</div>
);
}

Copy
Here we are saying if loading is true then
show <LoadingGif /> and in second line, we said !loading so
that returns false in this case so <Content /> will not load and
first statement is true so <LoadingGif /> will load!

Ternary Operator
What we were doing in previous example was basically
just if statement. We don't have else so we were
using if as else too. Let's learn how to do both(if/else)!
Same thing can be done like this:

function App() {

const loading = true;

return (
<div className="App">
{loading ? <LoadingGif /> : <Content />}
</div>
);
}
Copy
We are saying if loading is true then show <LoadingGif />, else
show <Content />, simple!
Syntax:

condition ? true : false

REACT LISTS
In React we render lists with loop
map()

An example of map:

function App() {
const languages = ['JS', 'Python', 'Java', 'C', 'C++',
'C#'];

return (
<div className="App">
{languages.map((language) => {
return <div>I love {language}</div>
})}
</div>
);
}

Copy
Output:
Keys
With keys React keep record of elements. This ensures that if an
item is updated or removed, only that item will be re-rendered
instead of the entire list. Example:

function App() {

const languagesDict = [
{ id: 1, language: 'JS' },
{ id: 2, language: 'Python' },
{ id: 3, language: 'Java' },
{ id: 4, language: 'C' },
{ id: 5, language: 'C++' },
{ id: 6, language: 'C#' }
];

return (
<div className="App">
{languagesDict.map((language) => {
return <div key={language.id}>
{language.id}. {language.language}
</div>
})}
</div>
);
}

Copy
Output:

REACT FORMS
React Forms are mostly like normal HTML forms, except we
use state in this to handle inputs.

Handling Forms
In React all the data is handled by component and stored in
component state. We can change state with event handlers in
the onChange attribute, like this:
import { useState } from 'react';

function Form() {
const [email, setEmail] = useState('');

return (
<form>
<label>
Enter your email: <input type="email"
value={email} onChange={(e) =>
setEmail(e.target.value)} />
</label>
</form>
)
}

export default Form;

Copy

Submitting Form
We can submit form with onSubmit attribute for the <form>

import { useState } from 'react';

function Form() {
const [email, setEmail] = useState('');

const handleSubmit = (e) => {


e.preventDefault();
alert(`Your email is: ${email}`)
}

return (
<form onSubmit={handleSubmit}>
<label>
Enter your email: <input type="email"
value={email} onChange={(e) =>
setEmail(e.target.value)} />
</label>
<input type="submit" />
</form>
)
}

export default Form;

Copy

Multiple Inputs
We don't have to make multiple states for multiple inputs, we can
save all values in one, like this:

import { useState } from 'react';

function Form() {
const [data, setData] = useState({});

const handleChange = (e)=>{


setData({...data, [e.target.name]: e.target.value})
}
const handleSubmit = (e) => {
e.preventDefault();
alert(`Your email is: ${data.email} and your name is:
${data.name}`)
}

return (
<form onSubmit={handleSubmit}>
<label>
Enter your email: <input type="email"
name='email' value={data.email}
onChange={handleChange} />
</label>
<label>
Enter your name: <input type="text" name='name'
value={data.name} onChange={handleChange} />
</label>
<input type="submit" />
</form>
)
}

export default Form;

Copy
Here in handleChange we used Spread Operators. We are
basically saying keep whole data as it was, just change this name's
value. Then it is saved as an object so we are getting that
by data.email and data.name.

REACT ROUTER
React Router
React router is used for page routing as React App doesn't include
it as default.

Add React Router


To install React router, run this in your terminal:

npm i -D react-router-dom

Copy

Creating Multiple Routes


To do this first we need to create multiple files and to keep code
clean, we will make a folder and make all the pages there, hence
we will create a folder named pages in src.

Folder Structure:
src/pages/:

 Home.js
 Blogs.js
 Contact.js
 Nopage.js

Usage
Now we will make routes in src/index.js, like this:

import React from 'react';


import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from "react-
router-dom";
import reportWebVitals from './reportWebVitals';
import Home from "./pages/Home";
import Blogs from "./pages/Blogs";
import Contact from "./pages/Contact";
import NoPage from "./pages/NoPage";

export default function App() {


return (
<BrowserRouter>
<Routes>
<Route index element={<Home />} />
<Route path="/blogs" element={<Blogs />} />
<Route path="/contact" element={<Contact />} />
<Route path="*" element={<NoPage />} />
</Routes>
</BrowserRouter>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);

reportWebVitals();

Copy
Home.js
Make all the Navigation links using <Link> tag, like this:

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


const Home = () => {
return (
<>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/blogs">Blogs</Link>
</li>
<li>
<Link
to="/contact">Contact</Link>
</li>
</ul>
</nav>
</>
)
};

export default Home;

Copy
Blogs.js

const Blogs = () => {


return <h1>Blogs</h1>;
};
export default Blogs;

Copy
Contact.js

const Contact = () => {


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

export default Contact;

Copy
NoPage.js

const NoPage = () => {


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

export default NoPage;

Copy
This is made for any route that doesn't exist. To show 404 error
there!

REACT MEMO
By default React re-renders components again and again.
Using memo will stop that if props have not changed.
Problem

When we make components like Navbar, Footer, they re-render


even if there is no change in them. To test this you can make a
Navbar component and import it. Put a console.log, if it is
logging, it means navbar is re-rendering.
Solution

So what's the solution for this? Because this re-rendering is just


wastage of resources.
memo is a simple solution for this! What memo does is, it just
monitors if props have changed, if they have it re-renders, if
they haven't it doesn't render again.
props is an object and javascript is very fast in comparing
objects as it doesn't compare the whole object, it just checks
the address!

Importing memo

To use it, first we need to import memo. It can be imported like


this:

import { memo } from "react";

Copy

Using memo

Everything remains the same, just when you are exporting the
Navbar, you have to wrap it in memo, like this:

export default memo(Navbar);

REACT CSS STYLE


REACT CSS STYLING
There are three ways to style in React:

1. Inline Styling
2. CSS Stylesheets
3. CSS Modules
Inline Styling

To inline style an element, we can make a Javascript Object, like


this:

const App = () => {


return (
<>
<h1 style={{ backgroundColor: "purple"
}}>CodeWithHarry</h1>
</>
);
}

Copy
In this first curly brace is to write javascript and second is to
make a javascript object. We can also write it like:

const App = () => {

const h1Style = {
backgroundColor: 'purple',
color: 'white'
}

return (
<>
<h1 style={h1Style}>CodeWithHarry</h1>
</>
);
}

Copy
Note: CSS property name must be camelCase. background-
color would be backgroundColor
CSS Stylesheets

You can save the whole CSS in a separate file with file
extension .css and import it in your application.
App.css
body {
background-color: 'purple';
color: 'white';
}

Copy
Here we are writing CSS, so we don't need to make JS Object or
do it in camelCase.
Index.js
Just import it like this:

import './App.css'

Copy
CSS Modules

In this you don't have to worry about name conflicts as it is


component specific. The CSS is available only for the file in
which it is imported.
Make a file with extension .module.css,
example: index.module.css
Make a new file index.module.css and insert some CSS into it,
like this:

.button {
background-color: 'purple';
color: 'white';
}

Copy
Import it in component like this:

import styles from './index.module.css';

const Home = () => {


return (
<button className={styles.button}>Click me!
</button>
)
};

export default Home;

REACT HOOKS
Hooks were added to React in version 16.8. Hooks let you use
state and other React features without writing a class.
Although states have largely replaced classes in React, there is no
plan of removing classes from React.
Things you need to keep in mind while using hooks:

 You must import hook first


 You must import it from react
 Hooks can only be called in React Function Components,
meaning:

// import statements
// Can't call here
const Blogs = () => {
// Can call here
return <h1>Blogs</h1>;
};

export default Blogs;

Copy

 Hooks cannot be conditional


 Hooks cannot work in React Class Components
 Hooks can only be called at the top level of a component,
meaning it can't be called from inside a block, i.e. {}. So,
can't be called inside if, loops or any block, example:

const Blogs = () => {


// Can call here
if (true){
// Can't call here
}
return <h1>Blogs</h1>;
};

export default Blogs;

REACT USESTATA
useState is a Hook that lets you add React state to function
components.

Importing useState
To use useState, first we need to import useState and initialize
it, you can import it from react like this:

import { useState } from "react";

Copy

Initializing useState
You can initialize state like this:

import { useState } from "react";


const App = () => {
const [name, setName] = useState('')
};

Copy
useState takes initial state as argument and gives a state and
a function(setName in this case) to update that state as we can't
directly change/update a state. Also, these state names are just
like variables, hence you can name them anything you like.
Reading a state

As mentioned earlier, it returns a state and a function to


change/update that state. Hence, everything is stored in name.
We can read states just like variables:

import { useState } from "react";

const App = () => {


const [name, setName] = useState('')

return <h1>My name is {name}</h1>


};

Copy
Updating a state

To update state we use the function it returns to update state,


in this case: setName. State can be updated like this:

import { useState } from "react";

const App = () => {


const [name, setName] = useState('')
setName('Lovish')
return <h1>My name is {name}</h1>
};

Copy
What can state hold?

Like normal variables, state can hold any datatype like strings,
numbers, booleans, arrays, objects, objects in arrays, arrays in
objects. For example:

import { useState } from "react";

const App = () => {


const [data, setData] = useState({
name: 'Lovish',
age: 21
})

return <h1>My name is {data.name} and my age is


{data.age}</h1>
};

Copy
Updating Objects and Arrays in State

import { useState } from "react";

const App = () => {


const [data, setData] = useState({
name: 'lovish',
age: 21
})
return <>
<h1>My name is {data.name} and my age is
{data.age}</h1>
<button onClick={() => setData({ ...data, name: 'CWH'
})}>Click Me</button></>
};

export default App;

Copy

REACT USEEFFECT
The useEffect Hook allows you to perform side effects in your
components.
useEffect accepts two arguments. The second one is optional.
Runs on every render:

import { useState, useEffect } from "react";

function Home() {
const [count, setCount] = useState(0);

useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});

return <h1>I have rendered {count} times!</h1>;


}

export default Home;

Copy
Runs on first render:

import { useState, useEffect } from "react";

function Home() {
const [count, setCount] = useState(0);

useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
}, []);

return <h1>I have rendered {count} times!</h1>;


}

export default Home;

Copy
Runs when data changes:

import { useState, useEffect } from "react";

function Home() {
const [count, setCount] = useState(0);
const [data, setData] = useState('');
const handleChange = (e) => {
setData(e.target.value)
}

useEffect(() => {
setCount((count) => count + 1);
}, [data]);

REACT USECONTEXT
useState is a Hook that lets you add React state to function
components. useContext helps to manage states globally, i.e.
between components.
Problem

Suppose there is a button in <Navbar /> Component which


affects something in <Home /> Component. Problems:
In this case, state can't be held in <Navbar /> or <Home />, it
will be in App.js
To access it, we have to pass it like a prop to the components,
and if the component is within 3-4 components, we have to pass
it to everyone as shown in image below:
Solution - Create Context

It's a hook so first we need to import it from react and


initialize it! To do this, write:

import { createContext } from "react";

const StateContext = createContext()

Copy
Context Provider

Now we need to wrap the component tree that need the state
Context in a Provider. It's like the Provider will provide the state
to every component in that tree which is wrapped in Provider.

function App() {
const [state, setState] = useState('true');

return (
<StateContext.Provider value={state}>
<h1>{`Hi! My state is ${state}!`}</h1>
<Home state={state} />
</StateContext.Provider>
);
}

Copy

useContext hook
First we need to import it:

import { useState, createContext, useContext } from


"react";

Copy
To access useContext, you can do something like this:

function Home() {
const state = useContext(StateContext);

return (
<>
<h2>{`Hii! My state is ${state}! `}</h2>
</>
);
}

REACT USEREF
useRef keeps the value stored between renders.
In this, value changed doesn't cause a re-render.
It can also be used to access a DOM element directly.
Doesn't cause re-render

import { useState, useRef } from "react";


import ReactDOM from "react-dom/client";

function App() {
const [stateValue, setStateValue] = useState("");
const refValue = useRef("");

return (
<>

<h1>Will cause a re-render:</h1>


<button
onClick={()=>{setStateValue(Math.random())}}>state</butto
n> : {stateValue}

<h1>Will change but won't cause a re-render:</h1>


<button
onClick={()=>{refValue.current=Math.random()}}>ref</butto
n> : {refValue.current}

</>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Copy
In this, if you click on state button, state will update and it will
re-render, whereas if you click on ref, nothing visible will
happen, i.e. ref will change but it won't re-render. To verify
this, you can again click on state, it will again update and re-
render but this time ref has some value stored, so that will
display.

Accessing DOM elements with ref

import { useRef } from "react";


import ReactDOM from "react-dom/client";

function App() {
const inputElement = useRef();

const focusInput = () => {


inputElement.current.focus();
};

return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}

const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Copy
In this, we initialized a useRef. In jsx, we used an attribute
called ref to store reference, once we have reference then we
can use it anyway we want.
REACT USEREDUCER
useReducer is similar to useState hook.
It lets you write your custom state logic.
It lets you pass dispatch down instead of callbacks resulting in
optimized performance for components that trigger deep
updates.
When to use useReducer?

useReducer is usually preferable to useState when you have


complex state logic, changing more than 2-3 states in a
function.
Syntax

const [state, dispatch] = useReducer(reducer,


initialState);

Copy
Here reducer is a function which contains your custom state
logic and initialState is as name suggests, it's initial state.
As you can see useReducer returns the current state and
a dispatch method.
Here is an example:

import { useReducer } from "react";

const initialData = {
lowercase: '',
uppercase: '',
spaces: ''
}

const reducer = (state, action) => {


switch (action.type) {
case 'LOWERCASE':
return {...state, [action.payload.name]:
action.payload.value.toLowerCase()}
case 'UPPERCASE':

REACT USECALLBACK
REACT USECALLBACK
React useCallback Hook returns a memoized callback function.
It is done so that it does not need to be recalculated resulting in
improved performance.
If we don't use useCallback function would run on every render.
This helps us to memoize resource intensive functions so that
they will not automatically run on every render.
With useCallback Hook, memoized function only runs when any
of its dependencies update.
When to use useCallback?

You may think we can use memo and stop a component from re-
rendering but if there is a case where you are passing a
function as prop to a component, then it will re-render
irrespective of memo. It is because of something called
"referential equality". In this every time a component re-
renders, its function gets recreated. Hence, memo is working but
because function is getting recreated, component will re-render.
To avoid this, we can use useCallback!
Like this:

const handleState = useCallback(() => {


setState({...state, type: 'CONFIRMED'});
}, [state])

Copy
Like this we are memoizing the function and only letting it run
when the dependency state changes!
REACT MEMO
React useMemo Hook returns a memoized value.
It is similar to useCallback Hook. The main difference
is useMemo returns a memoized value and useCallback returns
a memoized function.
The useMemo Hook only runs when any of its dependencies
update.
useMemo can improve performance big time.
When to use it?

Like if you have an expensive function like this:

const expensiveFunction = (num) => {


console.log("Calculating...");
for (let i = 0; i < 1000000000; i++) {
num += 1;
}
return num;
};

Copy
This function will run on every render resulting in slowing down
of everything. To prevent this, we can memoize it's result and
return it without calculating and only recalculate it when num
changes.
For this we will make a state number because we have to give
changing factor as dependency. Hence, code would be:

import { useMemo, useState } from "react";

const App = () => {


const [number, setNumber] = useState(0);
const calculation = useMemo(() =>
expensiveFunction(number), [number]);
return (
<div>
{calculation}
</div>
);
};

You might also like