Hybrid LiveView + React DataTable with sorting, filtering, and pagination
Real-time product inventory statistics
Interactive table with sorting, filtering, and pagination
Hybrid LiveView + React DataTable integration
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()
})
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 (...);
}
Python manages product data state and business logic
React handles sorting, filtering, pagination on client-side
Custom POST handler returns JSON instead of DOM patches