Home > other >  Render different component based on condition
Render different component based on condition

Time:02-02

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.

CodePudding user response:

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 />
    )}
  </>
);
  • Related