📊

Product DataTable Demo

Hybrid LiveView + React DataTable with sorting, filtering, and pagination

Live Stats

Real-time product inventory statistics

20
Total Products
15
Active
$489,506.76
Total Value
1
Low Stock

Product Inventory

Interactive table with sorting, filtering, and pagination

Implementation

Hybrid LiveView + React DataTable integration

views.py Python
from djust import LiveView
from django.http import JsonResponse

class ProductDataTableView(LiveView):
    """
    Hybrid LiveView + React DataTable
    Server manages data, React handles UI
    """
    use_dom_patching = False  # Use JSON

    def mount(self, request, **kwargs):
        self.products = self._generate_sample_products(20)

    def post(self, request, *args, **kwargs):
        """Return JSON instead of patches"""
        data = json.loads(request.body)
        event = data.get('event')

        # Call event handler
        handler = getattr(self, event, None)
        if handler:
            handler(**data.get('params', {}))

        # Return updated data
        return JsonResponse({
            'products': self.products,
            'stats': self._get_stats()
        })
DataTable.jsx React
function DataTable({ data, columns }) {
  const [sortCol, setSortCol] = useState(null);
  const [sortDir, setSortDir] = useState('asc');
  const [filter, setFilter] = useState('');
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);

  // Sort data
  const sortedData = useMemo(() => {
    if (!sortCol) return data;
    return [...data].sort((a, b) => {
      const comparison = a[sortCol] < b[sortCol] ? -1 : 1;
      return sortDir === 'asc' ? comparison : -comparison;
    });
  }, [data, sortCol, sortDir]);

  // Filter data
  const filteredData = useMemo(() => {
    if (!filter) return sortedData;
    return sortedData.filter(row =>
      columns.some(col =>
        String(row[col.key]).toLowerCase()
          .includes(filter.toLowerCase())
      )
    );
  }, [sortedData, filter]);

  // Paginate
  const paginatedData = useMemo(() => {
    const start = (page - 1) * pageSize;
    return filteredData.slice(start, start + pageSize);
  }, [filteredData, page, pageSize]);

  return (...);
}

How It Works

🗄️

Server Data Management

Python manages product data state and business logic

⚛️

React UI Components

React handles sorting, filtering, pagination on client-side

🔄

JSON API

Custom POST handler returns JSON instead of DOM patches