react-admin

repository·master·Indexed 12 days ago

https://github.com/marmelab/react-admin

A frontend framework for building single-page applications (SPAs) on top of REST or GraphQL APIs using React, TypeScript, and Material UI. It provides a complete set of building blocks for admin interfaces, including an Enterprise Edition with advanced features like AI-powered components (ra-ai), role-based access control (ra-rbac), and real-time notifications (ra-realtime).

Tokens
977.7K
Snippets
2.4K
Records
3K
Agent score
95%

What's inside react-admin

  1. Overview of the Headless SPA Framework for React

    master
    The headless framework provides battle-tested hooks and components designed to build high-performance single-page applications (SPAs). It is built on top of modern industry standards including react-query, react-hook-form, react-router, and TypeScript. It is designed to work with any REST or GraphQL API and serves as the foundation for projects like React-admin and shadcn-admin-kit.
  2. Navigate the react-admin documentation structure

    master

    The documentation is organized by functional area to help you find specific implementation details:

    • Architecture & Concepts: Core concepts like data fetching, security, and general architecture.
    • App Configuration: Setting up CoreAdmin, resources, and routing.
    • Data Fetching: Working with APIs and DataProviders.
    • Security: Authentication, authorization, and access control.
    • Views & Pages:
      • List Pages: Building list views, filtering, and pagination.
      • Creation & Edition: Forms, validation, and input components.
      • Show Pages: Detail views and field components.
    • Components:
      • Fields: Display components for various data types.
      • Inputs: Form input components and validation.
    • Internationalization: Multi-language support and localization.
    • Utilities: Shared utilities and common patterns.
  3. Explore supported Data Provider backends

    master

    React-admin uses a Data Provider architecture to interface with various API backends. There is a wide range of open-source Data Providers available for different technologies, ranging from REST and GraphQL to specialized databases like Firebase, Supabase, and Appwrite.

    If your backend is not listed, you can write your own Data Provider. This is a relatively quick process (often taking a couple of hours) and does not prevent you from using React-admin.

    Prototyping Tip: Because all Data Providers implement the same interface, you can start with a simple provider (like ra-data-fakerest) during early development and switch to your production provider (like ra-data-supabase or ra-data-simple-rest) later without changing your UI code.

  4. Explore Third-Party React-admin packages

    master

    Beyond the core and Enterprise packages, several third-party community packages are available to extend react-admin functionality:

    • react-admin-google-maps: Google Maps input and view components.
    • api-platform/admin: Specialized admin for APIs supporting Hydra Core Vocabulary.
    • ra-component-factory: Centralized configuration for field visibility, immutability, and re-ordering based on roles.
    • ra-resource-aggregator: Allows editing/creating/deleting multiple resources within a single view.
    • react-admin-import-csv: Adds a CSV file import button.
    • @bb-tech/ra-components: Provides hierarchical menus and specific inputs like Email, URL, and Phone.
    • Vycanis Modeler: Tool to generate React Admin applications from ER diagrams (ERD).
  5. Explore React-admin Enterprise Edition packages

    master

    React-admin Enterprise Edition provides specialized packages for advanced functionality. These modules can be integrated into your application to handle complex requirements like AI assistance, auditing, real-time collaboration, and advanced form layouts.

    Key Enterprise modules include:

    • @react-admin/ra-ai: AI-powered components for text completion and improvement in forms.
    • @react-admin/ra-audit-log: Tracking user actions and activity overview.
    • @react-admin/ra-calendar: Event management with drag-and-drop capabilities.
    • @react-admin/ra-editable-datagrid: Enhanced <Datagrid> with edit-in-place features.
    • @react-admin/ra-form-layout: Complex layouts like wizards, accordions, and autosave.
    • @react-admin/ra-json-schema-form: Form generation via JSON Schema.
    • @react-admin/ra-navigation: Advanced page/menu layouts and smart breadcrumbs.
    • @react-admin/ra-relationships: Specialized inputs for managing relationships (e.g., many-to-many via join tables).
    • @react-admin/ra-rbac: Role-Based Access Control that extends authProvider for fine-grained permissions.
    • @react-admin/ra-realtime: Real-time collaboration tools to prevent data loss and sync views.
    • @react-admin/ra-search: Omnibox search integration for multiple resources.
    • @react-admin/ra-tour: User onboarding and feature tutorials.
    • @react-admin/ra-tree: Components for managing hierarchical tree structures.
  6. What is the react-admin Store and how to use it

    master

    The react-admin Store is a global, synchronous, persistent key-value database used for storing user preferences (e.g., interface language, theme, UI state). It persists between page loads using browser localStorage (or memory storage if localStorage is unavailable) and is automatically emptied when a user logs out.

    It requires no setup and is available via several hooks. You can use it to manage simple UI states like toggling a panel or saving a user's preference.

    import { useStore } from 'react-admin';
    import { Button, Popover } from '@mui/material';
    
    const HelpButton = () => {
        // useStore(key, defaultValue)
        const [helpOpen, setHelpOpen] = useStore('help.open', false);
        return (
            <>
                <Button onClick={() => setHelpOpen(v => !v)}>
                    {helpOpen ? 'Hide' : 'Show'} help
                </Button>
                <Popover open={helpOpen} onClose={() => setHelpOpen(false)}>
                    Help Content
                </Popover>
            </>
        );
    };
  7. What is ra-core?

    master

    ra-core is a headless single-page application (SPA) framework for React designed to build admin panels, internal tools, dashboards, ERPs, and B2B applications.

    It manages the core business logic of an admin application, including:

    • Data Management: Fetching, editing, and relational data aggregation.
    • Navigation & Routing: Integrated with react-router.
    • Security: Authentication and authorization logic.
    • Internationalization: Multi-language support.
    • Form Management: State management and validation (via react-hook-form).
    • Performance: Intelligent caching and optimistic updates (via TanStack Query).

    Because it is headless, it does not provide a UI kit. You are free to use any design system such as Shadcn UI, Material UI, Ant Design, Chakra UI, or custom components. It is the engine behind frameworks like React-Admin (Material UI) and Shadcn Admin Kit (Shadcn UI).

  8. What is a Data Provider?

    master
    React-admin is backend agnostic. It uses an adapter pattern called Data Providers to connect to any API (REST, GraphQL, etc.). A Data Provider acts as a bridge between the react-admin components and your specific API implementation. You can use one of the 45+ existing adapters or write your own custom Data Provider to query your existing API.
  9. What is a Data Provider and how does it work?

    master

    A dataProvider is an adapter that interfaces between react-admin and your API. Instead of using fetch or axios directly in your components, you communicate through the dataProvider object. This allows react-admin to remain backend-agnostic, meaning it can work with REST, GraphQL, RPC, SOAP, or any other API dialect.

    The dataProvider is responsible for:

    1. Transforming react-admin method calls into HTTP requests.
    2. Converting API responses into the normalized format expected by react-admin.
    // Example of calling a data provider method directly
    const response = await dataProvider.getOne('posts', { id: 123 });
    console.log(response.data); // { id: 123, title: "hello, world" }
  10. What is an Auth Provider and how to implement it

    master

    An authProvider is an adapter that allows ra-core to connect to any authentication backend. It is a simple object containing methods that ra-core calls to handle authentication (login/logout) and authorization (checking credentials and permissions).

    If you are using TypeScript, you should use the AuthProvider type from ra-core to ensure your implementation is correct at compile-time.

    Required Methods

    • login(params): Sends credentials to the auth server.
    • checkError(error): Determines if a dataProvider error is an authentication error.
    • checkAuth(params): Validates if the user's credentials are still valid during navigation.
    • logout(): Removes local credentials and notifies the server.

    Optional Methods

    • getIdentity(): Returns the user's profile (e.g., id, fullName, avatar).
    • handleCallback(): Processes authentication callbacks for third-party providers (OAuth).
    • canAccess(params): Checks authorization for specific actions over a resource.
    • getPermissions(): Returns the user's permissions for permission-based authorization.
    import type { AuthProvider } from 'ra-core';
    
    const authProvider: AuthProvider = {
        // Implement required and optional methods here
    };
  11. Use Global Form Validation

    master

    You can apply validation to an entire form by passing a validate prop to the <Form> component. This function receives the entire record as input and must return an object where keys are field names and values are error messages (or translation keys).

    Key behaviors:

    • Translation Support: You can return translation keys (strings) or objects containing a message key and args for parameterized translations.
    • ArrayInput Support: For ArrayInput, you can return a single error message for the whole array or an array of error objects targeting specific children.
    • Limitation: You cannot use both form-level validation (validate on <Form>) and input-level validation (validate on <Input>) simultaneously due to react-hook-form constraints.
    const validateUserCreation = (values) => {
        const errors = {};
        if (!values.firstName) {
            errors.firstName = 'The firstName is required';
        }
        if (!values.age) {
            // Return translation key
            errors.age = 'ra.validation.required';
        } else if (values.age < 18) {
            // Return object for parameterized translation
            errors.age = {
                message: 'ra.validation.minValue',
                args: { min: 18 }
            };
        }
        // Target children in an ArrayInput
        if (!values.children || !values.children.length) {
            errors.children = 'ra.validation.required';
        } else {
            errors.children = values.children.map(child => {
                const childErrors = {};
                if (!child || !child.firstName) {
                    childErrors.firstName = 'The firstName is required';
                }
                return childErrors;
            });
        }
        return errors;
    };
    
    export const UserCreate = () => (
        <CreateBase>
            <Form validate={validateUserCreation}>
                <TextInput label="First Name" source="firstName" />
                <TextInput label="Age" source="age" />
                <ArrayInput label="Children" source="children">
                    <SimpleFormIterator>
                        <TextInput label="First Name" source="firstName" />
                    </SimpleFormIterator>
                </ArrayInput>
            </Form>
        </CreateBase>
    );