Skip to content
Advertisement

Setting state of nested array with React Hooks

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:

JavaScript

Advertisement

Answer

You need to make use of team index and update that particular teams value using spread syntax and slice like

JavaScript

or better you can just use map to update

JavaScript

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement