AoXNeR
AoXNeR

Reputation: 77

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.

Upvotes: 0

Views: 1552

Answers (2)

talm0r
talm0r

Reputation: 84

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>
)

}

Upvotes: 1

Prashant Shah
Prashant Shah

Reputation: 246

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.

Upvotes: 1

Related Questions