I have been working with React Hooks for a while, but the biggest problem for me is working with arrays.
I am making a register form for teams. Teams have players (array of strings).
The user should be able to add a team, and for each team, an input is shown with the current members in the team displayed above the input.
My question: How do I set the state of a nested array with React Hooks?
On the button click, it should (for now) add a string to the players array of the current team.
My Code:
interface ITeam {
id: string;
players: Array<string>;
}
export default function Team() {
const [teams, setTeams] = useState<Array<ITeam>>([{id: '1', players: ['a', 'b']}]);
return (
<div>
{teams.map((team, teamIndex) => {
return (
<div key={teamIndex}>
<h2>Team {teamIndex + 1}</h2>
<ul>
{team.players.map((player, playerIndex) => {
return (
<div key={playerIndex}>
{player}
</div>
);
})}
</ul>
<button onClick={() => setTeams([...teams, team.players.concat('c')])}>Add player</button>
</div>
);
})}
</div>
);
}