Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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,
        };
      }
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading