myselfmiqdad
myselfmiqdad

Reputation: 2606

Iterate through array and display React component one at a time

I have the following page:

const GalleryPage: NextPage = () => {
  const router = useRouter();
  const id = router.query.id as string;

  return (
    <Gallery id={id} imageUrl="someRandomImageUrl.png" />
  );
};

And within the Gallery Component, I have

...
return (
    <div>
      <Form
        onSubmit={handleSubmit}
        name="judging"
      >
        <input type="hidden" name="form-name" value="judging" />

        <Container text style={{ marginTop: '2em' }} textAlign="center">
          <Image src={galleryProps?.imageUrl} size="medium" verticalAlign="middle" />
          <Table singleLine>
            <Table.Header>
              <TableHeader />
            </Table.Header>

            <Table.Body>
              <TableRow
                title="Composition"
                name="composition"
                item={composition}
                setItem={setComposition}
              />
              <TableRow
                title="Creativity - Originality"
                name="creativity"
                item={creativity}
                setItem={setCreativity}
              />
              <TableRow
                title="Neatness - Finishing details"
                name="neatness"
                item={neatness}
                setItem={setNeatness}
              />
            </Table.Body>
          </Table>
        </Container>
        <Container text style={{ marginTop: '1em' }} textAlign="center">
          <p>
            <Button type="submit">Submit</Button>
          </p>
        </Container>
      </Form>
    </div>
  );

Where TableRow and TableHeader are custom components.

What I can't seem to make happen

I have an array of image URLs:

const imageUrls = ['firstImageUrl.png', 'secondImageUrl.jpeg', 'thirdImageUrl.png']

And for each item in the imageUrls, I want to display the Gallery component. And only once the form in the Gallery is submitted, do I want the next instance to display with the following image.

ie: firstcase: <Gallery id={id} imageUrl="firstImageUrl.png" /> once form submitted, second case secondcase: <Gallery id={id} imageUrl="secondImageUrl.jpeg" /> once form submitted, third case ...

Upvotes: 0

Views: 140

Answers (1)

Iosif
Iosif

Reputation: 822

You can create a state called galleryIndex that starts of as 0 and then to gallery you pass a function prop called onSumbit and inside there you increase the state galleryIndex by 1 and then inside the Gallery page you set imageUrl on Gallery component to be the element from the array imageUrls at the index galleryIndex

Upvotes: 1

Related Questions