Skip to main content

why in react arr.map works to render jsx but filter does not.

This is an interesting question that touches on a key aspect of how React renders elements. Let's break down why map() works for rendering JSX while filter() doesn't work in the same way.

  1. How map() works with JSX:

map() is commonly used in React because it creates a new array by transforming each element of the original array. When used with JSX, each transformation typically returns a JSX element, resulting in an array of JSX elements that React can render.

const items = ["apple", "banana", "orange"];
const listItems = items.map((item) => <li key={item}>{item}</li>);
// listItems is now an array of JSX elements
  1. Why filter() doesn't work the same way:

filter() creates a new array with all elements that pass a certain condition. It doesn't transform the elements; it only includes or excludes them based on the condition.

const items = ["apple", "banana", "orange"];
const filteredItems = items.filter((item) => item.length > 5);
// filteredItems is ['banana', 'orange'], still an array of strings, not JSX

even if you return different values let say

const items = ["apple", "banana", "orange"];
const filteredItems = items.filter((item) => item === "apple"); // ['apple']

const filteredItems = items.filter((item) => (item === "apple" ? "YES" : "NO")); // ["apple", "banana", "orange"]

/* do you why because filter will return values automatically filter will covert "YES" and "NO" into true and false. since both are true filter will return all items ,
but if you will return 1 and 0

*/
const filteredItems = items.filter((item) => (item === "apple" ? "YES" : 0)); // ["apple"]

// "YES" will convert to true and 0 will convert to false

Watch it here - https://youtu.be/9H5nMlco7bc?si=iDidRKOn8gk_fhdK