Using conditions to jump out of a map in map() in React
Using conditions in map() in React:
-
Calls the method on the array
map()
. -
Use
if
a condition to explicitly return if the condition is met. -
Otherwise return a different value or return
null
to render nothing.
export default function App() {
const arr = [1, 2, 3, 4, 5, 6];
return (
<div>
{arr.map((element, index) => {
if (element % 2 === 0) {
return <h2 key={index}>{element}</h2>;
}
return <h2 key={index}>X</h2>;
})}
</div>
);
}
We Array.map
iterate over an array using the method.
The function we pass to
map()
will be called with each element in the array and the index of the current iteration.
In each iteration, we check if the element is divisible by 2, if so, we return the element, otherwise, we return X.
If you don't need to render anything, return null
If you don't want to render anything in the else clause, you can return null.
export default function App() {
const arr = [1, 2, 3, 4, 5, 6];
return (
<div>
{arr.map((element, index) => {
if (element % 2 === 0) {
return <h2 key={index}>{element}</h2>;
}
// 👇️ render nothing
return null;
})}
</div>
);
}
The example renders numbers that are divisible by 2 and renders nothing otherwise.
Alternatively, we can use the ternary operator.
Using ternary operator with conditions in map()
This is a three-step process:
-
Calls the method on the array
map()
. - Use the ternary operator to check if a condition is true.
- The operator returns the value on the left of the colon if the condition is true, otherwise it returns the value on the right.
export default function App() {
const arr = [1, 2, 3, 4, 5, 6];
return (
<div>
{arr.map((element, index) => {
return element % 2 === 0 ? (
<h2 key={index}>{element}</h2>
) : (
<h2 key={index}>X</h2>
);
})}
</div>
);
}
We used if/else
a conditional ternary operator very similar to the statement.
If the expression before the question mark evaluates to true, then the value to the left of the colon is returned, otherwise the value to the right of the colon is returned.
In other words, if the element is divisible by 2, we return the element, otherwise we return X.
As in the previous example, if you want to return nothing in the else clause, you must return null.
export default function App() {
const arr = [1, 2, 3, 4, 5, 6];
return (
<div>
{arr.map((element, index) => {
return element % 2 === 0 ? <h2 key={index}>{element}</h2> : null;
})}
</div>
);
}
We used an index for the key prop in our examples, however, it is better to use a stable unique identifier if available.
React uses the key prop internally for performance reasons. It helps the library ensure that only changed array elements are re-rendered.
Having said that, unless you are dealing with tens of thousands of array elements, you won't see any noticeable difference.
Breaking out of map() loops in React (map() is just a slice of an array)
To break out of the map() loop:
- Call the slice() method on an array to get a portion of the array.
- Calls the map() method on a portion of an array.
- Iterate over a portion of an array.
export default function App() {
const employees = [
{id: 1, name: 'Alice', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
{id: 3, name: 'Carl', country: 'Canada'},
{id: 4, name: 'Delilah', country: 'Denmark'},
{id: 5, name: 'Ethan', country: 'Egypt'},
];
// 👇️ map() first 2 elements of array
return (
<div>
{employees.slice(0, 2).map((employee, index) => {
return (
<div key={index}>
<h2>name: {employee.name}</h2>
<h2>country: {employee.country}</h2>
<hr />
</div>
);
})}
</div>
);
}
Array.slice
method does not modify the original array, but creates a new array (a shallow copy of the original array).
We pass the following 2 parameters to the slice() method:
- startIndex The index of the first element to be included in the new array
- endIndex up, but not including this index
We specified a starting index of 0 and an ending index of 2, so we get the portion of the array that contains elements 0 and 1.
Even if the end index we provide to Array.slice
the method exceeds the length of the array, the method will not throw an error but return all the array elements.
const arr = ['a', 'b', 'c'];
const first100 = arr.slice(0, 100);
console.log(first100); // 👉️ ['a', 'b', 'c']
We are trying to get the first 100 elements of an array which contains only 3 elements.
As a result, the new array contains all 3 elements of the original array.
Map() is just a part of the array, use filter()
We can also map()
use Array.filter
the method before calling .
export default function App() {
const employees = [
{id: 1, name: 'Alice', country: 'Austria'},
{id: 2, name: 'Jiyik', country: 'China'},
{id: 3, name: 'Carl', country: 'Canada'},
{id: 4, name: 'Delilah', country: 'Denmark'},
{id: 5, name: 'Ethan', country: 'Egypt'},
];
// 👇️ map() LAST 2 elements of array
return (
<div>
{employees
.filter(employee => {
return (
employee.country === 'Belgium' || employee.country === 'Denmark'
);
})
.map((employee, index) => {
return (
<div key={index}>
<h2>name: {employee.name}</h2>
<h2>country: {employee.country}</h2>
<hr />
</div>
);
})}
</div>
);
}
The function we pass to filter()
the method is called for each element in the array.
In each iteration we check if the current object has a country attribute equal to Belgium or Denmark and return the result.
filter()
The method returns an array containing only those elements for which the callback function returns a true value.
In the example, map()
the method is called only with objects with id 2 and 4.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Using onChange event in React
Publish Date:2025/03/03 Views:148 Category:React
-
onChange 是 React 中最常见的输入事件之一。本文将帮助你了解它的工作原理。
Checkbox onChange in React
Publish Date:2025/03/03 Views:73 Category:React
-
本教程演示了如何从 React 中 onChange 事件的复选框发送值。
onDoubleClick in React
Publish Date:2025/03/03 Views:128 Category:React
-
本教程演示了如何在 React 中使用 onDoubleClick。
Show element or text on hover in React
Publish Date:2025/03/03 Views:186 Category:React
-
在 React 中悬停时显示元素或文本: 在元素上设置 onMouseOver 和 onMouseOut 属性。 跟踪用户是否将鼠标悬停在状态变量中的元素上。 根据状态变量有条件地渲染另一个元素。 import {useStat
Scroll to top of page in React.js
Publish Date:2025/03/03 Views:182 Category:React
-
在 React 中使用 window.scrollTo() 方法滚动到页面顶部,例如 window.scrollTo(0, 0) 。 window 对象上的 scrollTo 方法滚动到文档中的一组特定坐标。 import {useEffect} from react ; export default function App (
Applying global CSS styles in React applications
Publish Date:2025/03/03 Views:145 Category:React
-
要在 React 应用程序中应用全局 CSS 样式,请将 CSS 写入扩展名为 .css 的文件中,并将其导入 index.js 文件中。 全局 CSS 应该在 index.js 中导入,以确保它被加载到你的 React 应用程序的所有
Passing events and parameters to onClick in React
Publish Date:2025/03/03 Views:63 Category:React
-
在 React 中传递事件和参数 onClick: 将内联函数传递给元素的 onClick 属性。 该函数应获取事件对象并调用 handleClick 。 将事件和参数传递给 handleClick 。 const App = () = { const handleClick = ( e
How to remove event listeners in React
Publish Date:2025/03/03 Views:194 Category:React
-
在 React 中删除事件监听器: 在 useEffect 挂钩中添加事件侦听器。 从 useEffect 挂钩返回一个函数。 当组件卸载时,使用 removeEventListener 方法移除事件监听器。 import {useRef, useEffect} from r
Calling multiple onClick functions in React
Publish Date:2025/03/03 Views:105 Category:React
-
To call multiple onClick functions in React: Set the onClick attribute on the element. Call other functions in the event handler. The event handler can call as many other functions as needed. export default function App () { const s