Home > Net >  Compare string to multiple values gives always true
Compare string to multiple values gives always true

Time:12-21

I want to hide a Header component when I'm either on the login, register or confirmation page, but for some reason it only works properly when I give only one string to compare the path with.

Here is my code:

import { useState } from 'react';
import { Link, useLocation } from 'react-router-dom';
import Status from './auth/Status';

const Header = () => {
  const [menuIsOpen, setMenuIsOpen] = useState(false);
  const location = useLocation()

  if (location.pathname === '/login') { return null }
  return (
    <nav className="bg-gray-800 p">
        // nav content
    </nav >
  )
};

export default Header;

This works fine on the login screen. The header is hidden and after you login, the header shows up again.

But when I try this:

if (location.pathname === '/login' || '/signup' || '/signup/confirm') { return null }

The header is disabled throughout the whole application.

How can I solve this issue?

CodePudding user response:

The condition:

location.pathname === '/login' || '/signup' || '/signup/confirm'

...is interpreted as:

(location.pathname === '/login') || '/signup' || '/signup/confirm'

(See operator precedence)

...i.e. even if location.pathnameis different from '/login', the condition is truthy because the string '/signup' is truthy.

Hence your Header is always disabled.

Properly build your condition, e.g. using Array.prototype.includes:

if (['/login', '/signup', '/signup/confirm'].includes(location.pathname)) {}

CodePudding user response:

The correct condition would be:

location.pathname === '/login' || location.pathname === '/signup' || location.pathname === '/signup/confirm'
  • Related