SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Using state to navigate to another React component

I have a simple React app for displaying games.

It has 3 buttons across the top of the page that control where the user can go when clicked like this:

[Games]   |   [Create]    |    [Login]

For my GamesList.js, CreateGame.js, and LoginForm.js components.

The navigation is simply controlled with React hooks like this:

// *** GamerPagesNavigation.js

const [showGames, setGames] = useState(true);
const [showCreate, setCreate] = useState(false);
const [showLogin, setLogin] = useState(false);


const handleGamesClick = useCallback(e => { (setCreate(false) || setLogin(false) ) || setGames(true) });
const handleCreateClick = useCallback(e => { (setGames(false) || setLogin(false) ) || setCreate(true) });
const handleLoginClick = useCallback(e => { (setCreate(false) || setGames(false) ) || setLogin(true) });

<div>
    {showGames && <GamesList />}
</div>
<div>
    {showCreate && <CreateGame />}
</div>
<div>
    {showLogin && <LoginForm />}
</div>

And it works wonderfully! :)

So that works great!

But now, I have a button on my LoginForm.js component for logging in.

When submitted and authenticated, I want the user to be directed to the Login page.

But I can't figure out how to go from the LoginForm.js component to the CreateGame component.

Because my state is controlled in the GamerPagesNavigation.js component, I can't figure out how to get the state values in another component.

When I tried this in my LoginForm.js component, it said showCreate is undefined:

setCreate(true)

Which I get, because it's defined in a different React component file.

So is there a way to do this?

Thanks! :)

Upvotes: 0

Views: 64

Answers (2)

Ilias Aboubeker
Ilias Aboubeker

Reputation: 152

const [showGames, setGames] = useState(true);
const [showCreate, setCreate] = useState(false);
const [showLogin, setLogin] = useState(false);


const handleGamesClick = useCallback(e => { (setCreate(false) || setLogin(false) ) || setGames(true) });
const handleCreateClick = useCallback(e => { (setGames(false) || setLogin(false) ) || setCreate(true) });
const handleLoginClick = useCallback(e => { (setCreate(false) || setGames(false) ) || setLogin(true) });

<div>
    {showGames && <GamesList />}
</div>
<div>
    {showCreate && <CreateGame />}
</div>
<div>
    {showLogin && <LoginForm handleCreateClick={handleCreateClick}/>}
</div>

then inside LoginForm destructure it

const LoginForm = (props)=>{
 const {handleCreateClick}= props;
 const handleSubmit=()=>{
 // your form submission logic
 handleCreateClick()
}
return(
<form onSubmit={handleSubmit}>
//your form inputs 
</form>
)
}

Upvotes: 1

Yalung Tang
Yalung Tang

Reputation: 639

Pass the function via props

    <LoginForm onLogin={() => setCreate(true)} />

From LoginForm.js

call props.onLogin() when needed

Upvotes: 1

Related Questions