Home > OS >  Why is my conditional printing its condition value?
Why is my conditional printing its condition value?

Time:08-19

I have a conditional to show top nav only when logged in:

  const [adminState, setAdminState] = useState({
    loggedIn: 0,
  });
  return (
    <AdminState.Provider value={[adminState, setAdminState]}>
      {adminState.loggedIn && <TopNav />} <--- this line is printing 0 when logged out
      <Routes>
        <Route element={<ProtectedRoutes />}>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Route>
        <Route path="*" element={<PageNotFound />} />
      </Routes>
    </AdminState.Provider>
  );
}

export default App;

When logged out, it is printing the number "0" where the conditional is.

CodePudding user response:

Note: && is the logical AND operator, not the conditional operator.

Because 0 && <TopNav /> results in the value 0, and React renders numbers when you provide them as children. It's just null, undefined, and booleans that it doesn't render (docs).

Instead, either:

  1. Use false instead of 0 for the loggedIn flag; then your && expression will result in false and React won't display anything for that expression's result.

    Or

  2. Use the actual conditional operator:

    {adminState.loggedIn ? <TopNav /> : null}
    

CodePudding user response:

You can use JavaScript logical && operator so true && expression always evaluates to expression, and false && expression always evaluates to false.

Therefore, if the condition is true, the element right after && will appear in the output. If it is false, React will ignore and skip it.

Just change :

const [adminState, setAdminState] = useState({
    loggedIn: 0,
  });

to :

const [adminState, setAdminState] = useState({
    loggedIn: true,
  });
  • Related