Skip to main content

React

1 map and filter

In React, map and filter are JavaScript array methods that are commonly used to transform and filter arrays of data when rendering lists or implementing data filtering in components.

  1. map: The map method is used to iterate over an array and create a new array with transformed values. In the context of React, map is often used to generate a list of React components based on an array of data.

Here's an example of using map to render a list of items in a React component:

import React from 'react';

function ItemList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}

In this example, the items array is mapped using map, and for each item, a <li> element is rendered with the name property. The key prop is important to provide a unique identifier for each rendered item, helping React efficiently update and reconcile the list when the array changes.

  1. filter: The filter method is used to create a new array containing only the elements that pass a particular condition. In React, filter is often used to implement data filtering or searching functionality in components.

Here's an example of using filter to filter a list of items based on a search query in a React component:

import React, { useState } from 'react';

function ItemList({ items }) {
const [searchQuery, setSearchQuery] = useState('');

const filteredItems = items.filter((item) =>
item.name.toLowerCase().includes(searchQuery.toLowerCase())
);

return (
<div>
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="Search items"
/>
<ul>
{filteredItems.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}

In this example, an input field is provided to enter a search query. The searchQuery state variable is updated as the user types. The filteredItems variable is computed using filter, which checks if the name of each item includes the searchQuery, regardless of case. Only the matching items are rendered in the list.

By using map and filter in React components, you can easily transform and filter data to generate dynamic and interactive UIs based on array-based data sources.

2 States

In React, "state" refers to an object that holds data and determines how the components behave and render in response to user actions or other events. It represents the mutable part of a component's data.

States are used to store and manage component-specific data that can change over time. When a state value is updated, React automatically re-renders the component and its children to reflect the new state.

In React class components, state is typically defined in the constructor using the this.state object. In functional components, state can be managed using the useState hook introduced in React 16.8.

Here's an example of how state is used in a class component:

import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}

incrementCount() {
this.setState({ count: this.state.count + 1 });
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.incrementCount()}>Increment</button>
</div>
);
}
}

In this example, the Counter component has a state property called count, which is initially set to 0 in the constructor. The incrementCount method updates the state by incrementing the count value using setState. The updated state is automatically reflected in the rendered output.

Note that in functional components, the useState hook provides a similar way to manage state. Here's an example of using useState to achieve the same functionality as the previous example:

import React, { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

function incrementCount() {
setCount(count + 1);
}

return (
<div>
<p>Count: {count}</p>
<button onClick={incrementCount}>Increment</button>
</div>
);
}

In this functional component, the useState hook is used to define a count state variable and a setCount function to update it. The incrementCount function uses setCount to increment the count value, and the updated state is reflected in the rendered output.

3 props

In React, "props" (short for properties) are a way to pass data from a parent component to its child components. Props are read-only and cannot be modified by the child components.

When a component is rendered, you can pass props to it by providing attributes on the component's JSX tag. The props are then accessible within the component through the props object.

Here's an example of how to pass and access props in a React component:

import React from 'react';

function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}

function App() {
return <Greeting name="John" />;
}

In this example, the Greeting component receives a prop called name from its parent component (App). The value of name is set to "John" when the Greeting component is rendered.

Within the Greeting component, the value of name is accessed using props.name, and it is used to dynamically render the greeting message.

Props can be of any JavaScript data type, including strings, numbers, booleans, objects, or even functions. You can pass multiple props to a component by adding additional attributes to its JSX tag.

import React from 'react';

function UserInfo(props) {
return (
<div>
<h1>{props.name}</h1>
<p>Age: {props.age}</p>
<p>Email: {props.email}</p>
</div>
);
}

function App() {
return (
<UserInfo
name="John Doe"
age={30}
email="john.doe@example.com"
/>
);
}

In this example, the UserInfo component receives three props: name, age, and email. Each prop is accessed using props.propName within the component and used to render the user information.

Props are useful for passing dynamic data and configuring the behavior of child components based on the parent's state or other factors. They enable component composition and reusability by allowing different instances of a component to have different data and behavior.

4 Conditional Expressions

In React, you can use inline conditional expressions (also known as conditional rendering) to conditionally render components, elements, or values based on certain conditions. This allows you to dynamically control what gets rendered in the component's output.

There are a few ways to implement inline conditional expressions in React. Here are a few examples:

  1. Using the ternary operator: You can use the ternary operator (condition ? expression1 : expression2) to conditionally render different content based on a condition.
import React from 'react';

function Greeting({ isLoggedIn }) {
return (
<div>
{isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please log in.</h1>
)}
</div>
);
}

In this example, the Greeting component renders different heading elements based on the value of the isLoggedIn prop. If isLoggedIn is true, it renders the "Welcome back!" heading; otherwise, it renders the "Please log in." heading.

  1. Using the logical && operator: You can use the logical && operator to conditionally render content when a condition is true.
import React from 'react';

function UserProfile({ user }) {
return (
<div>
{user && (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
)}
</div>
);
}

In this example, the UserProfile component renders the user's name and email if the user prop is truthy. If user is falsy (e.g., null or undefined), nothing is rendered.

  1. Using variables or functions: You can assign conditional values to variables or use functions to conditionally compute values.
import React from 'react';

function MessageCount({ count }) {
const messageText = count === 1 ? 'message' : 'messages';

function renderMessageCount() {
if (count === 0) {
return <p>No messages.</p>;
} else {
return <p>{count} {messageText}</p>;
}
}

return (
<div>
{renderMessageCount()}
</div>
);
}

In this example, the MessageCount component determines the appropriate text to display based on the count prop. It assigns the singular or plural form of "message" to the messageText variable. It also uses a function, renderMessageCount, to conditionally render different content based on the value of count.

These are just a few examples of how you can use inline conditional expressions in React components. They provide a powerful way to control the rendering of components and elements based on dynamic conditions and data.

5 Event Handling in React

In React, event handling allows you to respond to user interactions and trigger specific actions or behaviors in your components. React provides a consistent and declarative way to handle events by using synthetic event objects and event handlers.

Here's an overview of how event handling works in React:

  1. Event Handling Syntax: In JSX, you can attach event handlers to elements using the onEvent attribute, where Event is the specific event you want to handle (e.g., onClick, onChange, onSubmit). The event handler is specified as a function or a method reference.
import React from 'react';

function Button() {
function handleClick() {
console.log('Button clicked!');
}

return <button onClick={handleClick}>Click me</button>;
}

In this example, the handleClick function is the event handler for the onClick event of the <button> element. When the button is clicked, the function is called, and the message "Button clicked!" is logged to the console.

  1. Event Object: React uses synthetic event objects that wrap native browser events to provide a consistent API across different browsers. The synthetic event object contains information about the event and methods for accessing event-related data.
import React from 'react';

function TextInput() {
function handleChange(event) {
console.log('Input value:', event.target.value);
}

return <input type="text" onChange={handleChange} />;
}

In this example, the handleChange function is the event handler for the onChange event of the <input> element. The event object is passed as an argument to the event handler, and you can access the input value using event.target.value.

  1. Class Components: When working with class components, event handlers are typically defined as methods of the component class. You can use the this keyword to access the component's properties and state within the event handler.
import React, { Component } from 'react';

class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}

handleClick() {
this.setState((prevState) => ({ count: prevState.count + 1 }));
}

render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.handleClick.bind(this)}>Increment</button>
</div>
);
}
}

In this class component example, the handleClick method is the event handler for the onClick event of the <button> element. It updates the component's state by incrementing the count value using setState.

  1. Preventing Default Behavior: In some cases, you may want to prevent the default behavior of a browser event, such as submitting a form or following a link. In React, you can call the preventDefault() method on the event object to stop the default behavior.
import React from 'react';

function Form() {
function handleSubmit(event) {
event.preventDefault();
console.log('Form submitted!');
}

return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
);
}

In this example, the handleSubmit function is the event handler for the onSubmit event of the <form> element. By calling event.preventDefault(), the default form submission is prevented, and the message "Form submitted!" is logged to the console instead.

These are the basics of event handling in React. By attaching event handlers to elements and utilizing synthetic event objects, you can respond to user interactions and create interactive and dynamic components.

6 keys

In React, the "key" is a special attribute that you can include when rendering lists of elements or components. The key helps React identify and track individual items in a list, allowing it to efficiently update and reconcile the list when the data changes.

Here are some key points about keys in React:

  1. Uniqueness: Each key should be unique among siblings in a list. React uses keys to determine whether an element is new, updated, or removed when the list is re-rendered.

  2. Stability: The key should be stable and not change between re-renders of the component. Changing the key value can cause unexpected behavior and may lead to issues with component state and lifecycle.

  3. Performance: Using keys helps React optimize the rendering process by providing a more efficient way to identify and update specific elements instead of re-rendering the entire list. It helps improve performance, especially when dealing with large lists.

  4. Choosing a key: When rendering a list, it's recommended to use a unique identifier from the data as the key. Common choices are unique IDs or indices. However, using indices as keys should be avoided if the list order can change, as it can negatively impact performance and cause issues during updates.

Here's an example of rendering a list with keys in React:

import React from 'react';

function ItemList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}

In this example, the items array is mapped to render a list of <li> elements. The key attribute is set to the id property of each item, assuming it provides a unique identifier for each item in the list. React uses the keys to efficiently update and reconcile the list when the items array changes.

Note that keys are primarily used when rendering lists of elements or components. For single elements or components that are not part of a list, the key attribute is not necessary.

Using appropriate keys in React helps optimize the rendering and updating process for lists, ensuring efficient and accurate UI updates when working with dynamic data.

7 forms

In React, forms are used to capture user input and handle form submissions. React provides a way to manage form state and handle form events using components and state management techniques. Here's an overview of how forms work in React:

  1. Form Component and State: Create a form component that represents the form in your application. The form component can be a functional component or a class component. In the component's state, define properties that correspond to the form inputs.
import React, { useState } from 'react';

function LoginForm() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');

// Event handler for input changes
const handleInputChange = (event) => {
const { name, value } = event.target;
if (name === 'username') {
setUsername(value);
} else if (name === 'password') {
setPassword(value);
}
};

// Event handler for form submission
const handleSubmit = (event) => {
event.preventDefault();
// Perform form submission logic
console.log('Submitted:', username, password);
};

return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
name="username"
value={username}
onChange={handleInputChange}
/>
</label>
<br />
<label>
Password:
<input
type="password"
name="password"
value={password}
onChange={handleInputChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
}

In this example, the LoginForm component manages the form state using the useState hook. Two input fields, username and password, are associated with their respective state values. The handleInputChange function updates the state as the user types in the input fields. The handleSubmit function is triggered when the form is submitted, preventing the default form submission behavior and logging the form values to the console.

  1. Input Change Handling: Attach an onChange event handler to each form input element to capture changes and update the corresponding state value.

  2. Form Submission Handling: Attach an onSubmit event handler to the <form> element to handle form submissions. Use event.preventDefault() to prevent the default form submission behavior and perform any necessary form submission logic within the event handler.

  3. Form Validation: Implement form validation by checking the form inputs' values and providing feedback to the user. You can use conditional rendering or external libraries to handle form validation in React.

  4. Controlled Components: In the example above, the form inputs are controlled components because their values are controlled by the component's state. Whenever the state changes, the input values are updated accordingly, and vice versa.

Note that the example above demonstrates a basic form implementation in React. In real-world scenarios, you may need to handle more complex form requirements, such as handling checkboxes, radio buttons, dropdowns, or multi-step forms. Additionally, you might consider using form validation libraries or building custom validation logic to ensure data integrity.

By managing form state and handling form events, React allows you to create interactive and dynamic forms in your applications.

8 Daynamic Inputa

In React, you can create dynamic inputs that allow users to add or remove input fields dynamically. This is useful when you want to collect variable-length data, such as a list of items or user-generated content. Here's an example of how to implement dynamic inputs in React:

import React, { useState } from 'react';

function DynamicInputs() {
const [inputs, setInputs] = useState([{ value: '' }]);

const handleInputChange = (index, event) => {
const values = [...inputs];
values[index].value = event.target.value;
setInputs(values);
};

const handleAddInput = () => {
const values = [...inputs];
values.push({ value: '' });
setInputs(values);
};

const handleRemoveInput = (index) => {
const values = [...inputs];
values.splice(index, 1);
setInputs(values);
};

const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted:', inputs.map((input) => input.value));
};

return (
<form onSubmit={handleSubmit}>
{inputs.map((input, index) => (
<div key={index}>
<input
type="text"
value={input.value}
onChange={(event) => handleInputChange(index, event)}
/>
<button type="button" onClick={() => handleRemoveInput(index)}>
Remove
</button>
</div>
))}
<button type="button" onClick={handleAddInput}>
Add Input
</button>
<button type="submit">Submit</button>
</form>
);
}

In this example, the DynamicInputs component manages an array of input values in its state using the useState hook. Each input value is an object with a value property. The handleInputChange function is used to update the corresponding input value when the user types in an input field.

The handleAddInput function adds a new input field by appending a new object with an empty value to the inputs array. The handleRemoveInput function removes an input field by removing the corresponding object from the inputs array.

The handleSubmit function is triggered when the form is submitted. It prevents the default form submission behavior and logs the input values to the console.

Within the render method, the inputs array is mapped to dynamically render the input fields. Each input field is associated with its corresponding value and an onChange event handler that calls handleInputChange with the index of the input field.

The "Add Input" button triggers the handleAddInput function to add a new input field dynamically. The "Remove" button, associated with each input field, triggers the handleRemoveInput function to remove the corresponding input field.

By managing the state of the input values and providing functions to add or remove inputs, you can create dynamic input fields that adjust to user needs in your React application.