Advertisement

React Filterable Image Gallery

| by Vladimir | 2 min read | code by Olga
Intermediate

Tech & Dependencies

HTML CSS Babel
React ReactDOM

Features

  • Multi-Select Filters
  • State Management
  • CSS Grid/Flexbox
  • Hover Effects

Browser Support

Chrome 80+ Edge 80+ Safari 13+ Firefox 75+

Core

This React Filterable Image Gallery is a clean, component-based solution for organizing visual content. Unlike simple “show/hide” scripts, it uses React’s state management to handle complex multi-criteria filtering. Users can toggle multiple categories (e.g., “Food” AND “Plants”) simultaneously, or reset everything with an “All” button. The UI is polished with pastel colors and smooth hover animations.

Core Technique

The functionality revolves around two arrays in the state: imgs (the data) and filters (the control logic).

1. Filter Logic in State

The application maintains an array of filter objects, each with a status boolean. When a user clicks a filter, the setFilter method toggles its status. Crucially, it then calls updateFilters() to check if all or none are selected (handling the “All” logic) and updateImgs() to derive the visible dataset.

updateImgs() {
  const { filters } = this.state;
  let newImgs = [];
  
  // Iterate through all images and check against active filters
  imgs.forEach((img) => { 
    filters.forEach((filter) => {  
      if ((img.tag == filter.name) && (filter.status == true)) {
        newImgs.push(img);
      }
    })
  });
  
  this.setState({ imgs: newImgs });
}

2. Component Composition

The UI is split into dumb components (Filters, Cards) and a smart container (App).

  • Filters: Renders the list of checkboxes styled as buttons. It receives the click handlers from the parent.
  • Cards: Renders the grid of images. It doesn’t know about filtering; it just displays whatever array it receives props.

3. CSS Animations

The appearance of images is smoothed out using a simple keyframe animation (@keyframes show). Whenever the list is re-rendered by React, the new elements mount with a fade-in effect.

@keyframes show {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

figure {
  animation: show .8s ease; /* Triggered on mount */
}

Browser Support

This is a standard React application. It works in all modern browsers.

Advertisement