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

React Notes

React creates a virtual DOM instead of directly manipulating the browser DOM. React components are independent and reusable code that return HTML. Components can receive data via props and re-render when their state changes.

Uploaded by

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

React Notes

React creates a virtual DOM instead of directly manipulating the browser DOM. React components are independent and reusable code that return HTML. Components can receive data via props and re-render when their state changes.

Uploaded by

Muthukrishnan N
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

How does React Work?

Instead of manipulating the browser's DOM directly, React creates a virtual DOM in memory,
where it does all the necessary manipulating, before making the changes in the browser
DOM.

React only changes what needs to be changed!

Current version of React.JS is V18.2

Current version of create-react-app is v5.0.1 (April 2022).

create-react-app includes built tools such as webpack, Babel, and ESLint.

To get an overview of what React is, you can write React code directly in HTML.

But in order to use React in production, you need npm and Node.js installed.

HTML className will be Pascalcase, and css name also in that way.
Classes
ES6 introduced classes.

A class is a type of function, but instead of using the keyword function to initiate it, we
use the keyword class, and the properties are assigned inside a constructor() method.
React Render HTML
React's goal is in many ways to render HTML in a web page.

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

The Render Function


The ReactDOM.render() function takes two arguments, HTML code and an HTML element.

The purpose of the function is to display the specified HTML code inside the specified HTML
element.

But render where?

There is another folder in the root directory of your React project, named "public". In this
folder, there is an index.html file.

You'll notice a single <div> in the body of this file. This is where our React application will
be rendered.

What is JSX?
JSX stands for JavaScript XML.

JSX allows us to write HTML in React.

JSX makes it easier to write and add HTML in React.


Coding JSX
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any
createElement() and/or appendChild() methods.

JSX converts HTML tags into react elements.

You are not required to use JSX, but JSX makes it easier to write React applications.

Expressions in JSX
With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript
expression. JSX will execute the expression and return the result:

One Top Level Element


The HTML code must be wrapped in ONE top level element.

So if you like to write two paragraphs, you must put them inside a parent element, like a
div element.

const myElement = <p>I am a paragraph.</p>;

If more than one element we have to wrap with () as below

const myElement = (
<div>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</div>

);
Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent
unnecessarily adding extra nodes to the DOM.

A fragment looks like an empty HTML tag: <></>.

const myElement = (
<>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</>

);

Elements Must be Closed


JSX follows XML rules, and therefore HTML elements must be properly closed.

Close empty elements with />

const myElement = <input type="text" />;

Attribute class = className


The class attribute is a much used attribute in HTML, but since JSX is rendered as
JavaScript, and the class keyword is a reserved word in JavaScript, you are not allowed to
use it in JSX.

Use attribute className instead.

Use attribute className instead of class in JSX:

const myElement = <h1 className="myclass">Hello World</h1>;


Conditions - if statements
React supports if statements, but not inside JSX.

To be able to use conditional statements in JSX, you should put the if statements outside of
the JSX, or you could use a ternary expression instead:

Option 1:

Write if statements outside of the JSX code:

Option 2:

Use ternary expressions instead:

Note that in order to embed a JavaScript expression inside JSX, the JavaScript must be
wrapped with curly braces, {}.
React Components
Components are like functions that return HTML elements.

React Components
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and return HTML.

Components come in two types, Class components and Function components

In older React code bases, you may find Class components primarily used. It is now
suggested to use Function components along with Hooks, which were added in React 16.8.
There is an optional section on Class components for your reference.

Create Your First Component


When creating a React component, the component's name MUST start with an upper case
letter.

Class Component
A class component must include the extends React.Component statement. This statement
creates an inheritance to React.Component, and gives your component access to
React.Component's functions.

The component also requires a render() method, this method returns HTML.

Example
Create a Class component called Car

class Car extends React.Component {


render() {
return <h2>Hi, I am a Car!</h2>;
}

}
Function Component
Here is the same example as above, but created using a Function component instead.

A Function component also returns HTML, and behaves much the same way as a Class
component, but Function components can be written using much less code, are easier to
understand, and will be preferred in this tutorial.

Example
Create a Function component called Car

function Car() {

return <h2>Hi, I am a Car!</h2>;

Rendering a Component
To use this component in your application, use similar syntax as normal HTML: <Car />

Props
Components can be passed as props, which stands for properties.

Props are like function arguments, and you send them into the component as attributes.

Example
Use an attribute to pass a color to the Car component, and use it in the render() function:

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

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


root.render(<Car color="red"/>);
Components in Components
function Car() {
return <h2>I am a Car!</h2>;
}

function Garage() {
return (
<>
<h1>Who lives in my Garage?</h1>
<Car />
</>
);

}
Components in Files
React is all about re-using code, and it is recommended to split your components into
separate files.

To do that, create a new file with a .js file extension and put the code inside it:

Note that the filename must start with an uppercase character.

Example

This is the new file, we named it "Car.js":

function Car() {
return <h2>Hi, I am a Car!</h2>;
}

export default Car;

Example
Now we import the "Car.js" file in the application, and we can use the Car component as if it
was created here.

import React from 'react';


import ReactDOM from 'react-dom/client';
import Car from './Car.js';

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

root.render(<Car />);
React Class Components
Before React 16.8, Class components were the only way to track state and lifecycle on a
React component. Function components were considered "state-less".

With the addition of Hooks, Function components are now almost equivalent to Class
components. The differences are so minor that you will probably never need to use a Class
component in React.

Even though Function components are preferred, there are no current plans on removing
Class components from React.

Props in the Constructor


If your component has a constructor function, the props should always be passed to the
constructor and also to the React.Component via the super() method.

Example
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>I am a {this.props.model}!</h2>;
}
}

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

root.render(<Car model="Mustang"/>);
React Class Component State
React Class components have a built-in state object.

The state object is where you store property values that belongs to the component.

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

The state object can contain as many properties as you like:

Example:
Refer to the state object anywhere in the component by using the
this.state.propertyname syntax:

Changing the state Object


Always use the setState() method to change the state object
To change a value in the state object, use the this.setState() method.When a value in
the state object changes, the component will re-render, meaning that the output will
change according to the new value(s).
Add a button with an onClick event that will change the color property:

InsideComponent{
changeColor = () => {
this.setState({color: "blue"});
}
}
Lifecycle of Components
Each component in React has a lifecycle which you can monitor and manipulate during its
three main phases.

The three phases are: Mounting, Updating, and Unmounting.

Mounting
Mounting means putting elements into the DOM.

React has four built-in methods that gets called, in this order, when mounting a component:

1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()

The render() method is required and will always be called, the others are optional and will
be called if you define them.

constructor
The constructor() method is called before anything else, when the component is initiated,
and it is the natural place to set up the initial state and other initial values.
The constructor() method is called with the props, as arguments, and you should always
start by calling the super(props) before anything else, this will initiate the parent's
constructor method and allows the component to inherit methods from its parent
(React.Component).
getDerivedStateFromProps
The getDerivedStateFromProps() method is called right before rendering the element(s)
in the DOM.

render
The render() method is required, and is the method that actually outputs the HTML to the
DOM.

componentDidMount
The componentDidMount() method is called after the component is rendered.

This is where you run statements that requires that the component is already placed in the
DOM.
Updating
The next phase in the lifecycle is when a component is updated.

A component is updated whenever there is a change in the component's state or props.

React has five built-in methods that gets called, in this order, when a component is updated:

1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()

The render() method is required and will always be called, the others are optional and will
be called if you define them.

Unmounting
The next phase in the lifecycle is when a component is removed from the DOM, or
unmounting as React likes to call it.

React has only one built-in method that gets called when a component is unmounted:

● componentWillUnmount()

componentWillUnmount
The componentWillUnmount method is called when the component is about to be removed
from the DOM.
React Props
React Props are like function arguments in JavaScript and attributes in HTML.

To send props into a component, use the same syntax as HTML attributes:

Example
Send the "brand" property from the Garage component to the Car component:

function Car(props) {

return <h2>I am a { props.brand }!</h2>;

function Garage() {

return (

<>

<h1>Who lives in my garage?</h1>

<Car brand="Ford" />

</>

);

If you have a variable to send, and not a string as in the example above, you just put the
variable name inside curly brackets:

function Garage() {
const carName = "Ford";
return (
<>
<h1>Who lives in my garage?</h1>
<Car brand={ carName } />
</>
);
}
React Hooks
Hooks were added to React in version 16.8.

Hooks allow function components to have access to state and other React features.
Because of this, class components are generally no longer needed.

Although Hooks generally replace class components, there are no plans to remove classes from
React.
React Events
ust like HTML DOM events, React can perform actions based on user events.

React has the same events as HTML: click, change, mouseover etc.

Adding Events
React events are written in camelCase syntax:

onClick instead of onclick.

React event handlers are written inside curly braces:

onClick={shoot} instead of onClick="shoot()".


React Router
Create React App doesn't include page routing.

Styling React Using CSS


There are many ways to style React with CSS, this tutorial will take a closer look at
three common ways:

● Inline styling
● CSS stylesheets
● CSS Modules

CSS Stylesheet
Create a new file called "Component-name.css" and Import the stylesheet in your
application:

import './Component-name.cs.css';

CSS Modules
Another way of adding styles to your application is to use CSS Modules.
CSS Modules are convenient for components that are placed in separate files.

The CSS inside a module is available only for the component that imported it, and you do
not have to worry about name conflicts.

Create the CSS module with the .module.css extension, example: my-style.module.css.

Create a new file called "my-style.module.css" and insert some CSS code in it:

Import the stylesheet in your component:

import styles from './my-style.module.css';


Styling React Using Sass
Sass files are executed on the server and sends CSS to the browser.

After creating react-app, need to install sass additionally using npm.


React slot
Children is a Normal Prop Too
Need for state hooks
Render HTML Content in React and JSX

Using dangerouslySetInnerHTML
How to pass data in on click function ?
React Lazy loading
Side effect function vs Pure function

Side effect function

Pure function, which does not make side effect


Problem with pure function in react(var not reactive
but console log change every click)
Solution with useMemo() function

useEffect() example
The useEffect with empty dependency, will run only
once when the component is rendered! (without
strict mode)

Strct mode will cause rendering it


We can use the useEffect() multiple times as well.
useCallback() example
Solution for that

You might also like