Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!