Kien Pham
Kien Pham

Reputation: 117

How to create dynamic state in for loop?

I have arrays of colors, with each color I have a gallery. I want to create and manage state for these galleries, so I can add/remove image for gallery easy.

I have code like this

var imgArr = new Array(colors.length)
for (var i = 0; i < colors.length; i++) {
    imgArr[i] = colors[i].imgs
    const [gallery[i], setGallery[i]] = React.useState()
    setGallery[i](imgArr[i])
}

but const [gallery[i], setGallery[i]] = React.useState() doesn't work.

How to resolve this issue?

Upvotes: 1

Views: 678

Answers (1)

Viet
Viet

Reputation: 12787

Don't write this inside a loop:

const [gallery[i], setGallery[i]] = React.useState()

The syntax is wrong. What you could use is a galleries state like this:

const [galleries, setGalleries] = useState([]);

Then:

setGalleries(colors.map((color) => color.imgs));

Sandbox: https://codesandbox.io/s/stupefied-roentgen-xk9zc?file=/src/App.js:547-600. Hope this answers your question.

Upvotes: 1

Related Questions