Search code examples
javascriptreactjsuse-state

How do I pass useState from one component to another?


I am trying to make a login modal that changes to the signup modal when the signup button is clicked within the Login.js. Currently, I have a header with a login button. When the login button is clicked, the current state is displayed (default value is ). I would like the signup button within Login.js to be able to update the state in order for that modal to .

Header.js:

import React, { useState } from 'react';
import Login from "../modals/Login";
import Signup from "../modals/Signup";

export default function Header() {

    const [lmodal, setModal] = useState(<Login />);

    return (
...
    {lmodal}
...
)
}

Login.js

import React, { useState } from 'react';
import Signup from "../modals/Signup";

export default function Login() {

return (
...
**// Clicking the button should change the state from Header.js to <Signup />**
 <button onClick={() => { setModal(<Signup />) }} className="btn btn-primary">Signup</button>
...
)
}

Thanks for the help in advance!


Solution

  • States and components are different in concept. What you coould possible do to reach the wanted behavior is to use the state to toogle the component, for exemple:

    import React, { useState } from 'react';
    import Login from "../modals/Login";
    import Signup from "../modals/Signup";
    
    export default function Header() {
    
        const [modal, setModal] = useState(false);
    
        return (
    ...
        {modal && <Login />}
        <Signup modal={modal} setModal={setModal}/>
    ...
    )}
    
    import React, { useState } from 'react';
    import Signup from "../modals/Signup";
    
    export default function Login({modal, setModal}) {
    
    return (
    ...
     <button onClick={() => setModal(true)} className="btn btn-primary">Signup</button>
    ...
    )
    }