React Notes
React Notes
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.
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 purpose of the function is to display the specified HTML code inside the specified HTML
element.
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.
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:
So if you like to write two paragraphs, you must put them inside a parent element, like a
div element.
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.
const myElement = (
<>
<p>I am a paragraph.</p>
<p>I am a paragraph too.</p>
</>
);
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:
Option 2:
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.
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.
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
}
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() {
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>;
}
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:
Example
function Car() {
return <h2>Hi, I am a Car!</h2>;
}
Example
Now we import the "Car.js" file in the application, and we can use the Car component as if it
was created here.
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.
Example
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>I am a {this.props.model}!</h2>;
}
}
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.
Example:
Refer to the state object anywhere in the component by using the
this.state.propertyname syntax:
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.
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.
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) {
function Garage() {
return (
<>
</>
);
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:
● 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:
Using dangerouslySetInnerHTML
How to pass data in on click function ?
React Lazy loading
Side effect function vs Pure function
useEffect() example
The useEffect with empty dependency, will run only
once when the component is rendered! (without
strict mode)