Home > Mobile >  React-select how to render only option values that are not undefined
React-select how to render only option values that are not undefined

Time:04-26

I need to render my Option values based on if/else that will show only option related to parameter from query

const renderLsit = useMemo(() => {
    return mediaCategories?.Entities?.map((category, _) => {
      if (
        category.CategoryTypeCode === MediaCategoryType.Other &&
        params.type === "categories"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      } else if (
        category.CategoryTypeCode === MediaCategoryType.Main &&
        params.type === "genre"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      }
    });
  }, [params, mediaCategories.Entities]);

But renderList contains undefined values after map and this is braking react-select. So it is returning something like this: enter image description here this is for else if and my Entities list dose not have undefined

CodePudding user response:

Could do a .filter() before .map()

return mediaCategories?.Entities?.filter(c => c !== undefined /*or whatever you want filter on*/).map((category, _) => {
      if (
        category.CategoryTypeCode === MediaCategoryType.Other &&
        params.type === "categories"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      } else if (
        category.CategoryTypeCode === MediaCategoryType.Main &&
        params.type === "genre"
      ) {
        return {
          value: category.CategoryId,
          label: category.CategoryName,
          index: category.CategoryId,
        };
      }
    });

CodePudding user response:

add filter before mapping to fillter out nulish values

 mediaCategories?.Entities?.filter(Boolean).map((category, _) =>

CodePudding user response:

In a more idiomatic / ES6 way:

const renderList = useMemo(() => {
    return mediaCategories?.Entities?.filter(
        ({ CategoryTypeCode }) =>
            (CategoryTypeCode === MediaCategoryType.Other &&
                params.type === "categories") ||
            (CategoryTypeCode === MediaCategoryType.Main &&
                params.type === "genre")
    ).map((category) => ({
        value: category.CategoryId,
        label: category.CategoryName,
        index: category.CategoryId,
    }));
}, [params, mediaCategories.Entities]);
  • Related