0

Es React. Programe un componente que es un botón hamburguesa, utilicé una librería para eso. Necesito que cuando presiono el botón se agregue la clase "is-active" y cuando lo presiono otra vez esa clase se borre. Logré hacerlo con este código pero estoy seguro que se puede hacer mucho más limpio, no se si guardando las clases en un array o algo así.

export default class Hambuerger extends React.Component{
constructor(props){
    super(props);
    this.state={
        className: "hamburger hamburger--minus"
    }
}
active = () => { 
    if(this.state.className === "hamburger hamburger--minus is-active"){
        this.setState({
            className: "hamburger hamburger--minus"
        });
    }else{
        this.setState({
            className: "hamburger hamburger--minus is-active"
        });
    }
}
render(){
    return(
        <button className={this.state.className} type="button" onClick={this.active}>
            <span className="hamburger-box">
                <span className="hamburger-inner"></span>
            </span>
        </button>
    )
}

}

1 respuesta 1

1

Yo lo haria con un Stateless component y usando hooks:

import React, { useState } from "react";

export default function Hamburguer() {

    const [active, setActive] = useState(false);

    return (
        <button className={`hamburger hamburger--minus ${active ? 'is-active' : ''}`} type="button" onClick={() => setActive(!active)}>
            <span className="hamburger-box">
                <span className="hamburger-inner"></span>
            </span>
        </button>
    )
}
1
  • Muchas gracias esto es lo que estaba buscando el 13 feb. 2021 a las 10:52

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.