I want to render a new table after onClick() event on a group of buttons. The table is supposed to be larger or smaller depending on the clicked button which represent the difficulty level of a game. I used two states: "selected" and "difficulty". The first one let the application redirect to "/game" route if a button has been clicked; the second one just keep track of the selected button and tells how much larger the table would be. I don't know how to modify difficulty with the proper value (1 for "easy", 3 for "difficult") in setDifficulty(selected_button) after calling handleSubmit in onCllick() function. This is my DifficultButtons.js:
const handleClick = (event) => {
event.preventDefault();
setSelected(true); //here i want to use setDifficulty(selected_button)
}
return (
<>
{selected ? <Link to={{
pathname: '/game',
state: {level : difficulty}
}} /> :
<ButtonGroup size="lg" className="d-grid gap-3 below-nav">
<Row className='main-font'>choose difficulty:</Row>
<Button variant="warning" size="lg" active level={1} onClick={handleSubmit>very Easy</Button>{' '}
<Button variant="warning" size="lg" active level={2} onClick={handleSubmit}>easy</Button>{' '}
<Button variant="warning" size="lg" active level={3} onClick={handleSubmit)}>Medium</Button>{' '}
</ButtonGroup>
}
Then in GameTable.js i would use setLocation() to take the state an render a table.
Without seeing the implementation of ButtonGroup and Button an easy way would be to curry the difficulty level in the click handler.
Update handleClick to curry a difficulty argument and return am onClick handler function. This closes over in callback scope a difficulty value for passing to the state updater function.
const handleClick = (difficulty) => (event) => {
event.preventDefault();
setSelected(true);
setDifficulty(difficulty);
};
Invoke handleClick and pass the appropriate difficulty level. This closes over the passed difficulty value and returns the onClick callback to attach button's onClick handler.
return (
<>
{selected ? (
<Link
to={{
pathname: '/game',
state: { level : difficulty }
}}
/>
) : (
<ButtonGroup size="lg" className="d-grid gap-3 below-nav">
<Row className='main-font'>choose difficulty:</Row>
<Button
variant="warning"
size="lg"
active
level={1}
onClick={handleSubmit(1)}
>
very Easy
</Button>
<Button
variant="warning"
size="lg"
active
level={2}
onClick={handleSubmit(2)}
>
easy
</Button>
<Button
variant="warning"
size="lg"
active
level={3}
onClick={handleSubmit(3)}
>
Medium
</Button>
</ButtonGroup>
)}
</>
);