Home > Mobile >  React controlling state with an outside component
React controlling state with an outside component

Time:06-23

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 >
            <button type="button"  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.

CodePudding user response:

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.

CodePudding user response:

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 >
        <button type="button"  onClick={callback}>Login</button>
    </div>
)

}

  • Related