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

Conditionally mapping two different arrays into a React component depending on boolean value

I currently have an array called options which is mapped into a React component like so:

{options.map((option) => (
   <Component key={option.code}></Component>
))}

However, I am trying to expand my component so that if a boolean value: shouldCount is true, then the optionsWithCount array is passed to the component instead of the options array. The component above has a lot more props etc than shown so I’d like to avoid just repeating the component with all of its props if possible.

Can anyone suggest a possible way of going about this?

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 :

Would using a utils function getOptions() work? It would take in the shouldCount flag as input and return the desired array. Example:

{ 
  getOptions(shouldCount).map((option) => (
    <Component key={option.code}></Component>
  ));
}

const getOptions = (shouldCount) => {
  return shouldCount ? optionsWithCount : options;
}
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