0% found this document useful (0 votes)
0 views18 pages

React Tutorial

React is an open-source JavaScript library by Facebook for building fast and dynamic user interfaces, particularly in single-page applications. It features a component-based architecture, a virtual DOM for performance, and supports both class and functional components with state management through hooks. The document also covers installation, project creation, props and state management, JSX syntax, and the differences between default and named exports.
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)
0 views18 pages

React Tutorial

React is an open-source JavaScript library by Facebook for building fast and dynamic user interfaces, particularly in single-page applications. It features a component-based architecture, a virtual DOM for performance, and supports both class and functional components with state management through hooks. The document also covers installation, project creation, props and state management, JSX syntax, and the differences between default and named exports.
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/ 18

React

 Introduction:
React is an open-source JavaScript library developed by Facebook for building user
interfaces, particularly for single-page applications where the aim is to create a fast,
responsive, and dynamic user experience. React allows developers to build web
applications that can update and render efficiently in response to data changes
without needing to reload the page. It is component-based, meaning the user
interface is built using encapsulated components that manage their own state,
making the code more predictable and easier to debug.

Key Features:

 Component-Based Architecture: Build encapsulated components that manage their


own state, then compose them to make complex UIs.
 Virtual DOM: React creates a virtual DOM in memory, where it performs all the
necessary updates before making changes to the real DOM, leading to improved
performance.
 Declarative: React makes it painless to create interactive UIs. Design simple views for
each state in your application, and React will efficiently update and render just the
right components when your data changes.
 Unidirectional Data Flow: Ensures that data changes are predictable and traceable.

Differnce between single page application and multi-page application:

Installation:
npm (Node Package Manager) is installed automatically when you install Node.js. npm is
the default package manager for Node.js, and it allows you to install and manage JavaScript
packages and dependencies for your projects.

Creating a React app without using a package manager like npm or yarn is not
recommended, as these tools provide essential functionalities for managing dependencies
and setting up the development environment.

npm (Node Package Manager)

 Manages packages and dependencies for Node.js projects.


 Used to install, update, and remove libraries.
 Creates and manages `package.json` files.

npx (Node Package Execute)

 Executes packages directly without installing them globally.


 Useful for running one-off commands or binaries from local `node_modules`.
 Simplifies running package binaries.

Differences

 `npm` is for managing and installing packages.


 `npx` is for executing packages without global installs.

To create project:
Priority command: npx create-react-app my-app
If want to work with typescript:
npx create-react-app my-app --template typescript
or configure manually:
npm create vite@latest my-app

To execute:
After running npm start, your development server should start, and you can view your React
application in your web browser, typically at http://localhost:3000.

NPM run build :


The command npm run build is used to create an optimized and minified version of your
React application for production deployment. Here’s why it’s important:

Purpose of npm run build:

1. Optimizes Code: It processes and optimizes your JavaScript, CSS, and other assets to
reduce their size and improve load times.
2. Minification: The build process removes unnecessary characters (like spaces and
comments) from the code, making it smaller and faster to load.
3. Bundling: It combines multiple files into fewer files, reducing the number of HTTP
requests required to load the app, which can enhance performance.
4. Environment Configuration: It sets the environment to "production," which often
includes optimizations specific to production use, like disabling development tools or
enabling performance improvements.
5. Static Files: The build command generates a build folder containing all the static files
needed to deploy your app to a web server.

Props:
Props (short for "properties") are a mechanism in React that allows components to receive
and pass data to one another. They are essentially arguments that you can pass to a
component, enabling you to customize its behavior and appearance.

Key Points:
 Immutable : Props are read-only, meaning a component cannot modify its own props.
This ensures that data flows in a unidirectional way, making the application more
predictable.
 Passing Data : You can pass any type of data as props, including strings, numbers, arrays,
objects, or even functions.
 Functionality : Props allow components to be dynamic and reusable by enabling them to
accept different values and behave differently based on those values.

Example:
When rendering a component, you might use props like this:

<WelcomeMessage name="Alice" />


In this example, the `WelcomeMessage` component receives the prop `name` with the value "Alice,"
allowing it to customize its message based on that name.

States:
State is a built-in object in React that allows components to manage and track their own data or
information that can change over time. It represents the dynamic parts of a component, which can
affect how it renders and behaves.

Key Points:

- Mutable : Unlike props, which are read-only, state can be changed within the component, allowing
for interactive and dynamic user interfaces.

- Initialization : State is typically initialized in a component's constructor (for class components) or


using the `useState` hook (for functional components).

- Reactivity : When the state changes, React automatically re-renders the component, ensuring that
the user interface stays in sync with the current data.

Example:

Here’s a simple example of using state in a functional component:

```jsx

import React, { useState } from 'react';

function Counter() {

const [count, setCount] = useState(0); // Initial state

return (

<div>

<p>You clicked {count} times</p>

<button onClick={() => setCount(count + 1)}>Click me</button>

</div>

);

```
In this example, the `Counter` component has a state variable `count`, which starts at 0. Each time
the button is clicked, the state is updated, and the component re-renders to show the new count.

Class Components:
Class components are one of the two main types of components in React, the other being functional
components. They are ES6 classes that extend the `React.Component` class and must include a
`render` method that returns React elements.

Key Characteristics of Class Components:

1. State Management : Class components can hold and manage their own state using `this.state`.
State is initialized in the constructor and updated with `this.setState()`.

2. Lifecycle Methods : Class components can implement lifecycle methods, which allow you to run
code at specific points in a component's lifecycle (e.g., when it mounts, updates, or unmounts).
Common lifecycle methods include:

- `componentDidMount()`: Called after the component is mounted.

- `componentDidUpdate(prevProps, prevState)`: Called after the component updates.

- `componentWillUnmount()`: Called before the component unmounts.

3. Props : Class components receive props as an argument to the constructor and access them using
`this.props`.

4. `this` Keyword : Class components use the `this` keyword to refer to the component instance. You
must bind methods to the class instance if you plan to pass them as event handlers.

Example of a Class Component:

Here's a simple example of a class component in React:

```jsx

import React from 'react';


class Greeting extends React.Component {

constructor(props) {

super(props);

this.state = {

name: 'Nikita'

};

// Lifecycle method

componentDidMount() {

console.log('Component mounted!');

// Method to update state

updateName = (e) => {

this.setState({ name: e.target.value });

};

render() {

return (

<div>

<h1>Hello, {this.state.name}!</h1>

<input

type='text'

value={this.state.name}

onChange={this.updateName}

/>

</div>

);

}
}

export default Greeting;

```

Breakdown of the Example:

- Constructor : The constructor initializes the component's state and binds methods if necessary.

- State : The state holds the name of the user, initialized to "Nikita".

- Lifecycle Method : `componentDidMount` is a lifecycle method that runs after the component is
mounted. You can place initialization code here.

- Event Handling : The `updateName` method updates the state when the input value changes. It
uses `this.setState()` to update the state.

- Render Method : The `render` method returns the JSX to be displayed.

Key Differences Between Class Components and Functional Components:

1. Syntax : Class components are defined as ES6 classes, while functional components are simple
functions.

2. State Management : Class components manage state using `this.state` and `this.setState()`, while
functional components use Hooks (like `useState`) to manage state.

3. Lifecycle Methods : Class components use lifecycle methods, while functional components use
the `useEffect` hook for similar behavior.

4. `this` Context : Class components require the use of `this` to access props and state, whereas
functional components do not.

Conclusion

Class components were the primary way to manage state and lifecycle in React before the
introduction of Hooks in React 16.8. While they are still supported and used in many applications,
functional components with Hooks have become the preferred way to build components due to
their simplicity and ease of use.

Function Components:
Functional components are one of the two main types of components in React, the other being class
components. Functional components are simpler and easier to read and write. They are essentially
JavaScript functions that return React elements, typically in JSX.

Here are some key characteristics of functional components:

1. Stateless by Nature : Originally, functional components were stateless, meaning they did not have
their own state. However, with the introduction of Hooks in React 16.8, functional components can
now manage state and side effects.

2. No Lifecycle Methods : Functional components do not have lifecycle methods like


`componentDidMount` or `componentDidUpdate`. Instead, you use Hooks like `useEffect` to handle
side effects.

3. Simpler Syntax : They are written as simple JavaScript functions, making them easier to read and
write.

4. Hooks : Functional components can use hooks like `useState`, `useEffect`, `useContext`, etc., to
add state and other features that were previously only available in class components.

Here’s an example of a simple functional component:

```jsx

import React from 'react';

function Greeting(props) {

return <h1>Hello, {props.name}!</h1>;

export default Greeting;

```

Here’s the same component with state management using hooks:


```jsx

import React, { useState } from 'react';

function Greeting() {

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

return (

<div>

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

<input

type='text'

value={name}

onChange={(e) => setName(e.target.value)}

/>

</div>

);

export default Greeting;

```

Key Differences Between Functional and Class Components

- Syntax : Functional components are functions, while class components are ES6 classes.

- State Management : Initially, functional components could not manage state, but with Hooks, they
can. Class components manage state using `this.state` and `this.setState`.

- Lifecycle Methods : Class components use lifecycle methods, while functional components use
`useEffect` to handle side effects.

- `this` Keyword : Functional components do not use `this`, making them less prone to bugs related
to `this` binding. Class components rely on `this` for accessing props, state, and lifecycle methods.
Functional components are generally preferred in modern React development due to their simplicity
and the power provided by Hooks.

Default Export

Definition : A default export is used to export a single value or function from a module. The
importing file can name the imported value whatever it chooses.

Example :

```javascript

// sayHello.js

function sayHello() {

return 'Hello, World!';

export default sayHello;

```

Usage :

```javascript

// main.js

import sayHello from './sayHello';

console.log(sayHello()); // Output: Hello, World!

```
Named Export

Definition : Named exports allow you to export multiple values or functions from a module. Each
exported value must be imported using its exact name.

Example :

```javascript

// functions.js

export function greet(name) {

return `Hello, ${name}!`;

export function farewell(name) {

return `Goodbye, ${name}!`;

```

Usage :

```javascript

// main.js

import { greet, farewell } from './functions';

console.log(greet('Nikita')); // Output: Hello, Nikita!

console.log(farewell('Nikita')); // Output: Goodbye, Nikita!

```

Differences Between Default and Named Exports


When to Use Which

- Use Default Export :

- When your module has a primary function or value that it is designed for.

- When you want to make the import simpler and more flexible for the consumer of the module.

- Use Named Export :

- When your module contains multiple functions or values that need to be accessed independently.

- When you want to provide a clear and specific API for the module, allowing consumers to import
only what they need.

Render components:

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


root.render(
<React.StrictMode>
<App />
<AppStarter/>
</React.StrictMode>
);

 The code initializes a React application by selecting a root DOM element, creating a root
for rendering, and rendering the specified components (App and AppStarter) within
React.StrictMode.
 Using StrictMode helps in identifying potential issues during development, ensuring that
your components follow best practices.

JSX:
JSX (JavaScript XML) is a syntax extension for JavaScript, primarily used with React. It allows you to
write HTML-like code within JavaScript files, making it easier to create and visualize the structure of
user interfaces.

How JSX Helps

1. Readable Syntax : JSX combines HTML and JavaScript, making it more intuitive to describe the UI
structure and components, which improves code readability.

2. Component Creation : It simplifies the creation of React components by allowing you to define
what the UI should look like directly in the code.

3. Babel Transformation : JSX is not valid JavaScript, but tools like Babel can transform it into
standard JavaScript. This process compiles the JSX into `React.createElement` calls, which React uses
to create and render elements.

4. Declarative UI : JSX helps in writing declarative code, allowing developers to describe how the UI
should look based on the current state, leading to more predictable and maintainable code.

Here’s a simple example of JSX:

import React from 'react';

function Greeting() {
return <h1>Hello, World!</h1>;
}

export default Greeting;

Another example:

function formatName(user) {
return user.firstName + ' ' + user.lastName;
}

const user = {
firstName: 'Harper',
lastName: 'Perez'
};

const element = (
<h1>
Hello, {formatName(user)}!
</h1>
);
In this example, the <h1>Hello, World!</h1> syntax is JSX. It makes it clear that this
component will render an <h1> element with the text "Hello, World!".

Specifying Attributes with JSX


You may use quotes to specify string literals as attributes:
const element = <a href="https://www.reactjs.org"> link </a>;

You may also use curly braces to embed a JavaScript expression in


an attribute:
const element = <img src={user.avatarUrl}></img>;

JSX Represents Objects


Babel compiles JSX down to React.createElement() calls.

These two examples are identical:

const element = (
<h1 className="greeting">
Hello, world!
</h1>
);

const element = React.createElement(


'h1',
{className: 'greeting'},
'Hello, world!'
);

performs a few checks to help you write bug-


React.createElement()
free code but essentially it creates an object like this:

// Note: this structure is simplified


const element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
JSX enhances the development experience in React by providing a clear and concise way to define UI
components, improving readability and maintainability of the code.

Differences Between JSX and HTML:

Example Comparison:

JSX Example:

const element = (
<div>
<h1 className="greeting">Hello, World!</h1>
<button onClick={() => alert('Clicked!')}>Click Me</button>
</div>
);

HTML Example:

<div>
<h1 class="greeting">Hello, World!</h1>
<button onclick="alert('Clicked!')">Click Me</button>
</div>

Summary

 JSX is a syntax extension for JavaScript used in React that allows embedding
JavaScript expressions and uses camelCase for attributes.
 HTML is a markup language for creating web pages and does not support JavaScript
expressions directly.
 JSX provides a more dynamic and powerful way to build user interfaces in React,
leveraging JavaScript’s capabilities while maintaining a familiar HTML-like syntax.

1. Rendering an Array of Strings


javascript
Copy code
const fruits = ["Apple", "Banana", "Cherry"];

function FruitList() {
return (
<ul>
{fruits.map(fruit => <li key={fruit}>{fruit}</li>)}
</ul>
);
}

2. Rendering an Array of Objects


javascript
Copy code
const users = [
{ id: 1, name: "Nikita", age: 20 },
{ id: 2, name: "Sneha", age: 22 },
];

function UserList() {
return (
<div>
{users.map(user => (
<div key={user.id}>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
</div>
))}
</div>
);
}

3. Rendering a Table from an Array of Objects


javascript
Copy code
const data = [
{ name: "Nikita", marks: 98, phone: "123" },
{ name: "Pratiksha", marks: 96, phone: "127" },
];

function DataTable() {
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Marks</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
{data.map((item, index) => (
<tr key={index}>
<td>{item.name}</td>
<td>{item.marks}</td>
<td>{item.phone}</td>
</tr>
))}
</tbody>
</table>
);
}

4. Rendering Object Properties Dynamically


javascript
Copy code
const person = { firstName: "Nikita", lastName: "Choudhari", age: 20 };

function PersonDetails() {
return (
<div>
{Object.entries(person).map(([key, value]) => (
<p key={key}>
<strong>{key}:</strong> {value}
</p>
))}
</div>
);
}

5. Rendering Nested Arrays


javascript
Copy code
const categories = [
{
title: "Fruits",
items: ["Apple", "Banana", "Cherry"],
},
{
title: "Vegetables",
items: ["Carrot", "Broccoli", "Spinach"],
},
];

function CategoryList() {
return (
<div>
{categories.map(category => (
<div key={category.title}>
<h3>{category.title}</h3>
<ul>
{category.items.map(item => (
<li key={item}>{item}</li>
))}
</ul>
</div>
))}
</div>
);
}

Babel:

Babel is a JavaScript compiler used to:

1. Transpile Modern JavaScript : Converts ES6+ code into a version


compatible with older browsers.
2. Transform JSX : Converts JSX syntax in React into standard JavaScript
function calls.
3. Polyfill New Features : Adds support for newer JavaScript features in
environments that lack them.
4. Customize with Plugins : Allows configuration of specific features
through plugins and presets.
5. Enhance Compatibility : Ensures code runs smoothly across different
browsers and environments.

Adding Bootstrap to React


ksad

Typescript

 s

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy