Why is my React Component always showing the same state?

Viewed 41

I am trying to use React and React Router to pass variables down to my RPGCompoent.

In this example, I am trying to pass a gameId.

So when I click each link, I should get one of these depending on which link(route):

game1 or game2 or game3

But when I click a link(route), it doesn't matter which one, I always just see this in the console output. * (this the browser console):

gameIdState:  {gameId: "game1"}

Here is my main React app:

import React from 'react';
import RPGComponent from './RPGComponent';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

export default function GamerTime() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/game_1">Game: Death Nights</Link>
          </li>
          <li>
            <Link to="/game_2">Game: Army Medic</Link>
          </li>
          <li>
            <Link to="/game_3">Game: Zombie Runner</Link>
          </li>
        </ul>

        <hr />
        <Switch>
          <Route path="/game_1"
            render={() => <RPGComponent gameId="game1" />}
          />
          <Route path="/game_2"
            render={() => <RPGComponent gameId="game2" />}
          />
          <Route path="/game_3"
            render={() => <RPGComponent gameId="game3" />}
          />
        </Switch>
      </div>
    </Router>
  );
}

Here is my RPGComponent:

import React, { useState, useEffect } from 'react';

const RPGComponent = (gameId) => {

    const [gameIdState, setGameIdState] = useState(gameId);

    console.log("gameIdState: ", gameIdState);

}

export default RPGComponent;
2 Answers

You don't have to create a hook for that if you pass gameId as a prop, you can just make it like this:

const RPGComponent = (props) => {
  console.log("gameIdState: ", props.gameId);

  return <div>test</div>;
};

Second thing - you don't render anything in RPGComponent. I created working example for you - link . So now when you click on the link it will show a div with test text inside it but in the console you will see actual gameId.

Firstly, gameId is fetched from props.

The parameter given to useState is much similar as setting state in constructor for a class component and isn't used to update the state on re-render. You can use useEffect to update state

const RPGComponent = (props) => {
  const { gameId } = props;
  const [gameIdState, setGameIdState] = useState(gameId);
  useEffect(() => {
    setGameIdState(gameId);
  }, [gameId]);
  console.log('gameIdState: ', gameIdState);
  return (
    <div>
      {gameIdState}
      {gameId}
    </div>
  );
};
Related