DEV Community

loading...

Simple Image Gallery using React, typescript and styled-components

renatobentorocha profile image Renato Rocha ・2 min read

In this post will be demonstrates an idea used to build a simple responsive image gallery on a React project using typescript and styled-components and without using media query.

For size values, percentage measures are used to maintain responsiveness.

""

""

The gallery's structure was made with a main container that using 100% of page width. Over the main container, we have two clickable labels, one on left and another on the right side. This labels will be used to move between the images.

When the component is rendered passing to it n images, then the structure bellow will be created n-1 over the main container.

So each one that structure has an id associated and the left label has an id for the previous and right label has an id for the next one. When one label is clicked the component state will be updated with the next or prev image id occasioning the rerender and apply the css to specific clicked label.


  function handleCheck(name: string) {
    setChecked(name);
  }

  function createInputRadio(index: number) {
    const id = `_${index}`;

    return styled.input.attrs({
      name: 'images',
      id,
      type: 'radio',
    })`
      &:checked {
        ~ #__${index} {
          visibility: visible;
          animation: scroll 1s ease-in-out;
        }
      }
    `;
  }

  function renderInputRadio(index: number) {
    const id = `_${index}`;
    const InputRadio = createInputRadio(index);

    return (
      <InputRadio
        key={index.toString()}
        checked={checked === id}
        value={checked}
        onChange={() => handleCheck(id)}
      />
    );
  }


Source code

Discussion

pic
Editor guide