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

Render different component based on condition

I am trying to render a component based on the condition.

exceptPath: ['home', 'person']
pathName = 'test'

return (
  <React.Fragment>
    {this.state.exceptPathNames.map((exceptPathName) => {
      console.log(exceptPathName);
      pathName === exceptPathName ? console.log('test') : <LinkGridLayout />;
    })}
  </React.Fragment>
);

If pathName is not "home" or "person" I want to return <LinkGridLayout /> else do not return anything.

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 :

If all you want to do is render a LinkGridLayout component for any pathName value that is not "home" or "person" (or any value in excludePath really) then I’d suggest the following refactor to check that no elements in the array equal the pathName, and if so, conditionally render LinkGridLayout.

Example:

exceptPath: ['home', 'person']
return (
  <>
    {!exceptPath.some((exceptPathName) => pathName === exceptPathName) && (
      <LinkGridLayout />
    )}
  </>
);

or

return (
  <>
    {exceptPath.every((exceptPathName) => pathName !== exceptPathName) && (
      <LinkGridLayout />
    )}
  </>
);
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