Home > Blockchain >  React JSX - Ternary operator with multiple or conditions
React JSX - Ternary operator with multiple or conditions

Time:12-21

I'm trying to render out a specific colour scheme for my footer based on the url pathname. The site only has 3 url's that require the colour scheme so I want to target them specifically. I'm wondering if there is a way to do it using the or/pipes operator or should I just put it in a switch statement?

var urlString = '/work' || '/wip' || '/journal';

<FooterContainer theme={ window.location.pathname == urlString  ? 'dark' : 'light' }>

This is my simplified code so far, just wanted to test that dark or light is returned on the component. It works for the /work url but the rest of them it doesn't.

CodePudding user response:

The condition '/work' || '/wip' || '/journal' will always return '/work' since it is considered a true value, so there is no need to check the other OR conditions. This is why it works for '/work' and nothing else.

I would like to recommend two approaches for this:

One is to write a straight forward function that returns true/false based on the pathname provided.

function checkUrl(pathname) {
    if (pathname === '/work' || pathname === '/wip' || pathname === '/journal') {
    return true;
  }
  return false;
}

<FooterContainer theme={ checkUrl(window.location.pathname)  ? 'dark' : 'light' }>

Or a second approach to make an array with the dark theme compatible pathnames and check if the current window.location.pathname is in this array.

var darkThemePathnames = ['/work', '/wip', '/journal'];
<FooterContainer theme={ darkThemePathnames.includes(window.location.pathname) ? 'dark' : 'light' }>

If you would like to shorten it even more then you can just do:

<FooterContainer theme={ ['/work', '/wip', '/journal'].includes(window.location.pathname) ? 'dark' : 'light' }>
  • Related