Conditional Rendering and Lists in React
In React, conditional rendering and lists are powerful tools for building dynamic and flexible interfaces. Let's explore how these features are used.
What is Conditional Rendering?
Conditional rendering in React refers to displaying different elements or components based on certain conditions. This can be achieved in several ways, primarily with JavaScript conditional structures like `if`, `else`, or the ternary operator.
- Ternary Operator: The ternary operator (condition ? true : false) can be used within JSX to conditionally render content.
- Logical && Operator: This operator is used to display an element only if a condition is true.
- If-Else Blocks: For more complex situations, if-else blocks can be used within rendering functions or methods.
Let's look at a simple example of conditional rendering using the ternary operator:
const Greeting = ({ isLoggedIn }) => { return ( <div> {isLoggedIn ? <p>Welcome, user</p> : <p>Please log in</p>} </div> ); };
Rendering Lists in React
List rendering is another essential concept in React. Often, applications need to represent a collection of items, such as a list of users, products, or tasks. React allows these lists to be rendered efficiently using the .map() method.
- Using .map(): To iterate over an array of data and render a component or element for each item.
- Using key: It is important to pass a unique key property for each element when rendering lists, as it helps React identify which items have changed.
An example of how to render a list of elements:
const TodoList = ({ todos }) => { return ( <ul> {todos.map(todo => ( <li key={todo.id}>{todo.text}</li> ))} </ul> ); };
In this case, todos is an array of objects, and each object has a unique id and text. We use map to generate an <li> for each task and assign ´ to each list item.
Combining Conditional Rendering and Lists
It is common to combine these two techniques in a React application. For example, if we are displaying a list of tasks and want to render only those tasks that are not completed, we can use conditional rendering inside a .map().
const TodoList = ({ todos }) => { return ( <ul> {todos.map(todo => ( todo.completed ? null : <li key={todo.id}>{todo.text}</li> ))} </ul> ); };
In this case, only uncompleted tasks are rendered, using conditional rendering inside .map().
What is conditional rendering in React? What is rendering in React? What is list rendering in React? Which of the following is a correct way to conditionally render a component in React? Conditional rendering React List rendering React Conditional components React If-else React Pure components React React component conditional render One React React lists