Search code examples
javascriptreactjscomparestring-comparison

React With Same String Comparison Using === Always Evaluates False


I have a component which uses some state passed down from a parent. The component will render if the user is logged in and a string matches. If so display otherwise dont. I've printed = in to console to ensured the strings had no spaces.

Though the conditional statement is correct "NOT OWNER" still shows when it should be "OWNER".

Here is the component simplified:

import React from "react";

const EditButton= ({
  isUserLoggedIn,
  username,
  sellersUsername,
}) => {
  return (
    <>
      {isUserLoggedIn&& username === sellersUsername? (
        <>OWNER</>
      ) : (
        <>NOT OWNER</>
      )}

      {console.log(`=${isUserLoggedIn}=`)}
      {console.log(`=${username}=`)}
      {console.log(`=${sellersUsername}=`)}
      {console.log(username=== sellersUsername)}
      {console.log(
        username.localeCompare(sellersUsername, "en", {
          sensitivity: "base",
        })
      )}
      {console.log(isUserLoggedIn&&username===sellersUsername)}
    </>
  );
};

export default GalleryEditButton;

The output:

// should evaluate to true but does not
=true=
=RandomTestUsername=
=RandomTestUsername=
false
0
false

Any ideas?


Solution

  • My suggestion is to check the typeOf the two variables. Because === is a strict checking that is case sensitive and also types sensitive.