Mi objetivo: cerrar mi barra de navegación al hacer clic en el botón que está dentro de la barra de navegación.
Parece que no puedo hacer que funcione. Si alguien puede explicarme qué estoy haciendo mal, ¡sería genial!
Aquí está mi barra de navegación:
import React, { useState } from 'react'; export default function Navbar() { const [showNav, setShowNav] = useState(true) return ( <div isOpen={showNav} 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> ) }Aquí está mi App.js
import './App.css'; import Navbar from './components/Navbar'; function App() { return ( <div className="flex"> <Navbar /> </div> ); } export default App;Para lograr lo que necesita, también puede usar la condición como esta:
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> } </>)No existe tal cosa como la propiedad isOpen en div
establezca la display en none en estilo si showNav es false Así:
import React, { useState } from 'react'; export default function Navbar() { const [showNav, setShowNav] = useState(true) return ( <div style={{display: showNav ? 'initial' : 'none'}} 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> ) } O use otra forma de ocultar un elemento (como la visibility , por ejemplo) vea aquí formas de ocultar un elemento en CSS
const [showNav, setShowNav] = useState(true) cambie a const [showNav, setShowNav] = useState("block");
onClick={() => setShowNav(false)} cambia a onClick={() => setShowNav("hidden")};