npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

react-filter-ui

v1.0.1

Published

A React filter component with advanced filtering capabilities

Readme

React Filter UI

A flexible React component library for building advanced filtering interfaces. This package provides a user-friendly UI for filtering data based on configurable schemas.

Features

  • Dynamic field selection based on schema
  • Multiple filter logic options (equals, contains, greater than, etc.)
  • Special input handling for dates, numbers, booleans, and references
  • Edit and remove existing filters
  • Theme customization through color hooks
  • MongoDB-compatible query generation

Installation

npm install react-filter-ui

or

yarn add react-filter-ui

Basic Usage

import React, { useState, useCallback } from 'react';
import { Filter } from 'react-filter-ui';

const MyDataTable = () => {
  // State for search parameters
  const [searchJson, setSearchJson] = useState({
    page: 1,
    limit: 10,
    search: {}
  });
  
  // State for pagination
  const [pagination, setPagination] = useState({
    page: 1,
    limit: 10,
    total: 0
  });
  
  // Define your data schema for filterable fields
  const filterSchema = [
    {
      serverKey: 'name',
      fieldLabel: 'Name',
      dbType: 'string',
      inputType: 'text',
      status: true,
      enabled: true,
      required: false
    },
    {
      serverKey: 'age',
      fieldLabel: 'Age',
      dbType: 'number',
      inputType: 'number',
      status: true,
      enabled: true,
      required: false
    },
    {
      serverKey: 'isActive',
      fieldLabel: 'Active',
      dbType: 'boolean',
      inputType: 'switch',
      status: true,
      enabled: true,
      required: false
    },
    {
      serverKey: 'createdAt',
      fieldLabel: 'Created Date',
      dbType: 'date',
      inputType: 'date',
      status: true,
      enabled: true,
      required: false
    }
  ];
  
  // Function to load data based on filters
  const loadData = useCallback((paginationParams, searchParams) => {
    // Make API call to your backend with the search parameters
    console.log('Loading data with:', paginationParams, searchParams);
    
    // Example API call:
    // api.fetchData(searchParams).then(response => {
    //   setData(response.data);
    //   setPagination({
    //     page: response.page,
    //     limit: response.limit,
    //     total: response.total
    //   });
    // });
  }, []);
  
  // Handle filter changes
  const handleFilterChange = useCallback((updatedSearchJson) => {
    // Prepare the formatted search JSON
    const formattedSearchJson = {
      page: 1, // Always reset to page 1 when filters change
      limit: pagination.limit || 10,
      search: (updatedSearchJson?.search || {})
    };
    
    // Move nested payload.search to top-level if needed
    if (updatedSearchJson?.payload?.search) {
      formattedSearchJson.search = updatedSearchJson.payload.search;
    }
    
    // Update the state
    setSearchJson(formattedSearchJson);
    
    // Schedule the API call (the loadData function will handle deduplication)
    loadData(formattedSearchJson, formattedSearchJson);
  }, [loadData, pagination.limit]);
  
  return (
    <div>
      <h1>My Data Table</h1>
      
      {/* Filter component */}
      {filterSchema.length > 0 && (
        <Filter
          schema={filterSchema}
          searchJson={searchJson}
          loadData={loadData}
          paginationData={pagination}
          collectionName="Users"
          onFilterChange={handleFilterChange}
        />
      )}
      
      {/* Your data table component goes here */}
      <div className="table-container">
        {/* Table implementation */}
      </div>
    </div>
  );
};

export default MyDataTable;

API Reference

Filter Component

| Prop | Type | Description | |------|------|-------------| | schema | Array | Array of field objects defining which fields can be filtered | | searchJson | Object | Current search parameters object | | loadData | Function | Function to call when filters change to reload data | | paginationData | Object | Pagination parameters like page, limit, total | | collectionName | String | Name of the collection/table being filtered (displayed in UI) | | onFilterChange | Function | Callback when filters change |

Schema Format

Each field in the schema array should have the following properties:

{
  serverKey: 'fieldName',        // Field key in the database
  fieldLabel: 'Field Label',     // Human-readable label
  dbType: 'string',              // Data type: 'string', 'number', 'date', 'boolean', 'ref' 
  inputType: 'text',             // UI input type
  status: true,                  // Whether field is available
  enabled: true,                 // Whether field is enabled
  required: false                // Whether field is required
}

Generated Query Format

The component generates MongoDB-compatible queries in the format:

{
  page: 1,
  limit: 10,
  search: {
    $and: [
      { fieldName: { $eq: "value" } },
      { age: { $gte: 21 } }
      // More conditions...
    ]
  }
}

Customizing Colors

The component uses the useColors hook to support theming. You can customize the colors by storing primaryColor and secondaryColor in localStorage:

// Example to set custom colors
const userData = {
  userData: {
    primaryColor: { hex: '#4a90e2' },
    secondaryColor: { hex: '#ffffff' }
  }
};

localStorage.setItem('imzUser', JSON.stringify(userData));

Advanced Features

Using FilterUI directly

For more control, you can use the FilterUI component directly:

import { FilterUI } from 'react-filter-ui';

// ...

<FilterUI
  schema={transformedSchema}
  activeFilters={activeFilters}
  setActiveFilters={setActiveFilters}
  onFilterChange={handleFilterChange}
  searchJson={searchJson}
  loadData={loadData}
  paginationData={pagination}
/>

Using the utility functions

import { 
  buildMongoQuery, 
  buildCompoundQuery,
  getLogicOptions,
  needsSpecialValueHandling 
} from 'react-filter-ui';

// Build a MongoDB query for a field
const query = buildMongoQuery('age', '$gte', 18, schema.schema.fields);

// Combine multiple queries
const queries = [
  { name: { $eq: 'John' } },
  { age: { $gte: 18 } }
];
const compoundQuery = buildCompoundQuery(queries);

License

MIT