简体   繁体   中英

Using multiple conditions in ternary operator to stop rendering component on specific routs

I have a component - side menu. I want to have it on all pages except singIn and singUp page. The way I choose to do it is to use "useLocation" and check location.pathname before rendering component. It looks something like that:

let location = useLocation().pathname;
  return (
location !== '/signin' && '/signup' ? (
  <div>sidemenu</div>
) : (
  <>
  </>
)

But it works only with first statement. Is it possible to pass multiple statements? Or may be there is another method not to render component on two/three specific pages?

Any boolean expression is valid in a ternary.

However, location !== '/signin' && '/signup' is parsed like:

(location !== '/signin') && ('/signup')

So you should instead write:

`location !== '/signin' && location !== '/signup'

Also, instead of the syntax

(expression) ? (
  <div>sidemenu</div>
) : (
  <>
  </>
)

if you don't want anything to be rendered in the false case, you can just use:

return (expression) && (<div>sidemenu</div>)

which will return false and not render anything if the expression is false, or if the expression is true it will render your div.


Also, a nice syntax for checking lists of path names is to use includes , like so:

['/signin', '/signup'].includes(useLocation().pathname)

then you have a one-liner that is easily extensible if you decide you want to add another path

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM