JSX is a syntax extension for JavaScript that allows you to write HTML-like code in your JavaScript files.
const element = <h1>Hello, world!</h1>;
Components are the building blocks of React applications. They can be functional or class-based.
function MyFunctionalComponent() {
return <h1>Hello, world!</h1>;
}
const MyFunctionalComponentWithProps = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
Props are short for properties, and are used to pass data from one component to another.
function MyComponent(props) {
return <h1>Hello, {props.name}!</h1>;
}
<MyComponent name="John" />
State is used to store and manage data within a component.
import { useState } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
Lifecycle methods are methods that get called at certain points in a component's lifecycle.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log('Component did mount.');
}
componentDidUpdate() {
console.log('Component did update.');
}
componentWillUnmount() {
console.log('Component will unmount.');
}
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>Increment</button>
</div>
);
}
}
React Hooks are functions that allow you to use state and other React features in functional components. Here are some examples of React Hooks and how they work: useState The useState Hook allows you to add state to your functional components. It returns an array with two elements: the current state and a function to update the state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the example above, we define a count state variable with an initial value of 0, and a function setCount that updates the count variable. When the button is clicked, the setCount function is called with the new value of count + 1, causing the component to re-render with the updated count value.
The useEffect Hook allows you to run side effects in your functional components. It takes a function as its first argument that will be executed after every render, and an optional array of dependencies as its second argument.
import { useState, useEffect } from 'react';
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = "You clicked $ {count} times";
}, [count]);
return (
<div>
<p>You clicked {count} times.</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
In the example above, we use the useEffect Hook to update the document title after every render. The second argument to useEffect is an array with a single value, count. This means that the effect will only be run when the count value changes, reducing unnecessary updates.
The useReducer Hook is an alternative to useState for managing complex state in your functional components. It allows you to define a state and a reducer function that can update the state based on different actions
import { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>You clicked {state.count} times.</p>
<button onClick={() => dispatch({ type: 'increment' })}>
Click me
</button>
<button onClick={() => dispatch({ type: 'decrement' })}>
Click me
</button>
</div>
);
}
In the example above, we define an initial state object with a count property, and a reducer function that can update the state based on different actions. We use the useReducer Hook to define the state and the reducer, and dispatch actions to update the state when the buttons are clicked.
In React, events are similar to DOM events, but there are some syntax differences. React provides a cross-browser compatible API for handling events. To handle events in React, you can add an event listener to a component using a special syntax provided by React. You pass a function as a property to the element, which will be called when the event occurs.
import React, { useState } from 'react';
function Button() {
const [count, setCount] = useState(0);
const handleClick = () => {
setCount(count + 1);
};
return (
<button onClick={handleClick}>
Click me ({count})
</button>
);
}
In the above example, we have a Button component that displays a button and a count. We use the useState hook to manage the count state. The handleClick function is called when the button is clicked, which updates the count state using the setCount function. The onClick attribute on the button element is where we attach the handleClick function to the button click event. When the button is clicked, the handleClick function is executed, which updates the state and triggers a re-render.
In React, conditional rendering is the process of rendering different content based on certain conditions. There are several ways to implement conditional rendering in React, but some of the most common methods are: 1.If statement: You can use a simple if statement to conditionally render content in React. 2.Ternary operator: You can also use a ternary operator to conditionally render content. 3.&& operator: You can use the && operator to conditionally render content as well.
function Greeting(props) {
if (props.isLoggedIn) {
return <h1>Welcome back!</h1>;
}
return <h1>Please log in.</h1>;
}
function Greeting(props) {
return (
<div>
{props.isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please log in.</h1>
)}
</div>
);
}
function Greeting(props) {
return (
<div>
{props.isLoggedIn && <h1>Welcome back!</h1>}
{!props.isLoggedIn && <h1>Please log in.</h1>}
</div>
);
}
These are just a few examples of how you can implement conditional rendering in React. There are many other ways to conditionally render content, depending on your specific needs.
To render a list of items in React, we can use the map method to loop through an array and return a new array of elements. Each element should have a unique key property to help React optimize updates.
function ListExample() {
const items = ['apple', 'banana', 'cherry'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
}
To handle a form in React, we need to listen for the onChange event of the input elements and update the state of the component. We also need to listen for the onSubmit event of the form element to handle the form submission.
function FormHandling() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log(Name: $ {name}, Email: $ {email});
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<label>
Email:
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}
In this example, we use the useState hook to store the form values (name and email). We also listen for the onChange event of the input elements to update the state. When the form is submitted, we prevent the default behavior of the form and log the form values to the console.
Custom hooks are a way to extract reusable logic from a component so that it can be shared across multiple components. Custom hooks are functions that use React's built-in hooks to provide some custom functionality.
import { useState } from 'react';
function useCounter(initialValue) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return [count, increment, decrement];
}
In this example, the useCounter hook takes an initial value for the counter as a parameter, initializes the counter state using the useState hook, and returns an array with three values: the current count, an increment function that increases the count, and a decrement function that decreases the count.We can then use this custom hook in a component:
import React from 'react';
import useCounter from './useCounter';
function Counter() {
const [count, increment, decrement] = useCounter(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
Thank You