React Tutorial
React Tutorial
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:
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.
Differences
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.
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:
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.
- Reactivity : When the state changes, React automatically re-renders the component, ensuring that
the user interface stays in sync with the current data.
Example:
```jsx
function Counter() {
return (
<div>
</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.
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:
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.
```jsx
constructor(props) {
super(props);
this.state = {
name: 'Nikita'
};
// Lifecycle method
componentDidMount() {
console.log('Component mounted!');
};
render() {
return (
<div>
<h1>Hello, {this.state.name}!</h1>
<input
type='text'
value={this.state.name}
onChange={this.updateName}
/>
</div>
);
}
}
```
- 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.
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.
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.
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.
```jsx
function Greeting(props) {
```
function Greeting() {
return (
<div>
<h1>Hello, {name}!</h1>
<input
type='text'
value={name}
/>
</div>
);
```
- 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() {
```
Usage :
```javascript
// main.js
```
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
```
Usage :
```javascript
// main.js
```
- 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.
- 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:
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.
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.
function Greeting() {
return <h1>Hello, World!</h1>;
}
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!".
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
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.
function FruitList() {
return (
<ul>
{fruits.map(fruit => <li key={fruit}>{fruit}</li>)}
</ul>
);
}
function UserList() {
return (
<div>
{users.map(user => (
<div key={user.id}>
<h2>{user.name}</h2>
<p>Age: {user.age}</p>
</div>
))}
</div>
);
}
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>
);
}
function PersonDetails() {
return (
<div>
{Object.entries(person).map(([key, value]) => (
<p key={key}>
<strong>{key}:</strong> {value}
</p>
))}
</div>
);
}
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:
Typescript
s