I have a React component that shows details of a soccer game when that game is clicked on in a table, called GameData
. The table is part of another component, and it updates a variable that GameData
uses to show the data. That variable is global, so using useState()
inside of GameData
doesn't work. How do I make GameData
re-render when the variable updates/changes?
Here is what my GameData
component is currently:
let gameToDisplay = {};
function displayGameData(gameId) {
gameToDisplay = gameData.find(game => game.id === gameId);
// This function runs when a game in the table is clicked. This part updates and works as expected.
}
function GameData() {
const [gdDisplay, setgdDisplay] = useState(true);
function handleDetailClick() {
setgdDisplay(!gdDisplay);
}
return (
<div className='GameData box'>
<h2>Game Details</h2>
<div className='Links'>
<ButtonGroup variant="contained" aria-label="outlined primary button group">
<Button onClick={handleDetailClick}>{gdDisplay ? 'Less' : 'More'} details</Button>
</ButtonGroup>
</div>
{gdDisplay ? (
<p className='data'>
// Data display that gets data from gameToDisplay
</p>
) : (
<></>
)}
</div>
)
}
Yes, the button approach works, but you have to click the button twice for the data to update. I'm trying to change the data inside of <p className='data'>
when gameToDisplay
is changed. How can I watch for that variable to change and re-render <p className='data'>
when that happens?