Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
React controlling state with an outside component

React newbie here, I have a component for login which has two states (logged and not), and a button, a button click makes a form appear for the user.

function Main() {

    const [state, setState] = useState(false);
    function buttonClick(event) {
        state = !state;
    }

    return (
    <div id='main'>
        <p id='main-body'>{lorem}</p>
        { state ? <LoginForm /> : <LoginButton />}
    </div>
 )
}

my issue is that the onClick itself (and the button) are in another component:

function LoginButton() {
    return (
        <div class="btn-centered">
            <button type="button" class="btn btn-outline-primary btn-lg btn-centered" onClick={}>Login</button>
        </div>
    )
}

Have I understood the concept wrongly? How do I achieve the result I want with the outside component? Thanks a lot for any help, I'd VERY appreciate explanations so I can learn.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can pass buttonClick method in login button component like this

<LoginButton onClick={buttonClick} />

and inside Loginbutton component you can do something like this

<button type="button" ... onClick={props.onClick}>Login</button>

so when you click login button it will trigger you buttonClick method.

about 4 years ago · Juan Pablo Isaza Denunciar

0

the LoginButton should get props and return a callback to the Main that will switch the state and you should also use useState to change the state in order to change the DOM,

thats how it should look

function Main() {

const [state, setState] = useState(false);
function buttonClick(event) {
    setState((prev) => !prev);
}

return (
    <div id='main'>
        <p id='main-body'>{lorem}</p>
        { state ? <LoginForm  /> : <LoginButton callback={buttonClick} />}
    </div>
)

function LoginButton(props) {
    const {callback} = props;
return (
    <div class="btn-centered">
        <button type="button" class="btn btn-outline-primary btn-lg btn-centered" onClick={callback}>Login</button>
    </div>
)

}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda