score:1

create a button to open, outside the if.

codesandbox

heres the code


import react, { usestate } from "react";

export default function navbar() {
  const [shownav, setshownav] = usestate(true);

  return (
    <>
      {!shownav && (
        <button
          classname="bg-primary w-32 h-12 rounded-lg text-white"
          onclick={() => setshownav(true)}
        >
          open navbar
        </button>
      )}
      {shownav && (
        <div classname="w-48 bg-gray-200 h-screen py-10">
          <button
            classname="bg-primary w-32 h-12 rounded-lg text-white"
            onclick={() => setshownav(false)}
          >
            close navbar
          </button>
          <h1>dashboard</h1>
          <h2>menu item</h2>
          <h2>menu item</h2>
          <h2>menu item</h2>
        </div>
      )}
    </>
  );
}


if you want you can make it one button only as well, just add some styling or a container wrapping everything up.

  return (
    <>
      <button
        classname="bg-primary w-32 h-12 rounded-lg text-white"
        onclick={() => setshownav(shownav)}
      >
        {shownav ? "close navbar": "opennavbar"}
      </button>
      {shownav && (
        <div classname="w-48 bg-gray-200 h-screen py-10">
          <h1>dashboard</h1>
          <h2>menu item</h2>
          <h2>menu item</h2>
          <h2>menu item</h2>
        </div>
      )}
    </>
  );

score:2

just use one state for opening and closing the navbar and pass it down from app.js to your navbar.

navbar:

import react, { usestate } from 'react';

export default function navbar({shownav, setshownav}) {

  return (
    <>
    {shownav && <div classname="w-48 bg-gray-200 h-screen py-10">
        <button classname="bg-primary w-32 h-12 rounded-lg text-white" onclick={() => setshownav(false)}>close navbar</button>       
        <h1>dashboard</h1>
        <h2>menu item</h2>
        <h2>menu item</h2>
        <h2>menu item</h2>
    </div>
    }
    </>
  )
}

app.js

import './app.css';
import navbar from './components/navbar';
import { usestate } from 'react';

function app() {
  const [shownav, setshownav] = usestate(true)

  return (
    <>
      <div classname="flex">
        <navbar shownav={shownav} setshownav={setshownav} />
        <button classname="bg-primary w-32 h-12 rounded-lg text-white" onclick={() => setshownav(true)}>open navbar</button>
      </div>
    </>
  );
}

export default app;

Related Query

More Query from same tag