Search code examples
javascriptreactjsnode.jsexpresssockets

Having trouble updating React child component when passed prop from parent is updated


In my backend, I have a socket.io, Node, Express setup that I have tested works properly, and is emitting the right number of broadcasts to the right client. socket.emit("team_set", gameInfo);

Now in the client, I have App.js which listens for this and sets a couple of states. These states are being passed down to child components (multiple layers down as well), and the components SHOULD be receiving new CSS "styles" to show but it isn't updating. I'm not sure what the issue is.

App.js

const [teamStyle, setTeamStyle] = useState({}); // a CSS style
const [seats, setSeats] = useState([]);
useEffect(() => {
    socket.on("team_set", (gameInfo) => {
      setTeamStyle(gameInfo.teamStyle);
      setSeats(gameInfo.seats);
      setGameStarted(true);
      console.log("team set called: ", gameInfo.teamStyle, gameInfo.seats);
    });

    return () => {
      socket.off('team_set'); 
    };
  }, []);
  ...

  return (
    <GameScreen
        socket={socket}
        username={username}
        seats={seats}
        teamStyle={teamStyle}
        numPlayers={numPlayers}
        gameStarted={gameStarted}
    />

GameScreen.jsx

...
return (
    <div className="gameScreen">
      <div>
        <PlayerBox 
          seats={seats}
          teamStyle={teamStyle} 
          numPlayers={numPlayers} 
          gameStarted={gameStarted}
        />
      ...

export default memo(GameScreen);

PlayerBox.jsx

return (
  <Player teamStyle={teamStyle}/>

Player.jsx

function Player(teamStyle) {  
  return (
    <div style={teamStyle}>
      <Fist />
    </div>
  )
}

export default memo(Player);

The teamStyle should be changing the color of my Player component but it isn't and I'm not sure why...


Solution

  • // change props. `teamStyle` to `{teamStyle}`
    function Player({teamStyle}) {  
      return (
        <div style={teamStyle}>
          <Fist />
        </div>
      )
    }
    
    export default memo(Player);