### Refine App Initialization with React Router Source: https://refine.dev/docs/index This snippet shows the main App component setup for a Refine application. It initializes Refine with a REST data provider, React Router, authentication provider, and i18n provider. It defines resources for 'products' and 'categories' and sets up authenticated routes for CRUD operations and public routes for authentication. ```tsx // file: /App.tsx import { Authenticated, type I18nProvider, Refine } from "@refinedev/core"; import dataProvider from "@refinedev/simple-rest"; import routerProvider, { CatchAllNavigate, NavigateToResource, } from "@refinedev/react-router"; import { BrowserRouter, Outlet, Route, Routes } from "react-router"; import CssBaseline from "@mui/material/CssBaseline"; import GlobalStyles from "@mui/material/GlobalStyles"; import { AuthPage, ErrorComponent, RefineSnackbarProvider, ThemedLayout, useNotificationProvider, } from "@refinedev/mui"; import { useTranslation } from "react-i18next"; import { authProvider } from "./authProvider"; import { Header } from "./components/header"; import { ColorModeContextProvider } from "./contexts/color-mode"; import { CategoryCreate, CategoryEdit, CategoryList, CategoryShow, } from "@/pages/categories"; import { ProductCreate, ProductEdit, ProductList, ProductShow, } from "@/pages/products"; function App() { const { t, i18n } = useTranslation(); const i18nProvider: I18nProvider = { translate: (key, params) => t(key, params).toString(), changeLocale: (lang: string | undefined) => i18n.changeLanguage(lang), getLocale: () => i18n.language, }; return ( }>
}> }> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> }> }> } /> } /> } /> } /> ); } ``` -------------------------------- ### Refine Internationalization Setup (TypeScript) Source: https://refine.dev/docs/index Configures i18next for internationalization in a React application using the @refinedev/core framework. It integrates with i18next-browser-languagedetector and i18next-xhr-backend to detect user language and load translations from JSON files. ```typescript import i18n from "i18next"; import detector from "i18next-browser-languagedetector"; import Backend from "i18next-xhr-backend"; import { initReactI18next } from "react-i18next"; i18n .use(Backend) .use(detector) .use(initReactI18next) .init({ supportedLngs: ["en", "de"], backend: { loadPath: "/locales/{{lng}}/{{ns}}.json", }, ns: ["common"], defaultNS: "common", fallbackLng: ["en", "de"], }); export default i18n; ``` -------------------------------- ### Product List with DataGrid and Refine MUI Source: https://refine.dev/docs/index This snippet defines the Product List page using Refine's `List` component and Material UI's `DataGrid`. It fetches product data and category information to display a table with columns for name, category, price, and actions. The category is displayed as its title, and the price is formatted as currency. Action buttons for showing, editing, and deleting products are included. ```tsx // file: /pages/products/list.tsx import { useMemo } from "react"; import { useGetLocale, useList, useTranslate, } from "@refinedev/core"; import { DataGrid, type GridColDef } from "@mui/x-data-grid"; import { DeleteButton, EditButton, List, NumberField, ShowButton, useDataGrid, } from "@refinedev/mui"; export const ProductList = () => { const { dataGridProps } = useDataGrid(); const locale = useGetLocale()(); const translate = useTranslate(); const { result: { data: categories }, query: { isLoading: categoryLoading } } = useList({ resource: "categories", pagination: { mode: "off", }, }); const columns = useMemo( () => [ { field: "name", flex: 1, headerName: translate("products.fields.name"), minWidth: 300, }, { field: "category", flex: 1, headerName: translate("products.fields.category"), minWidth: 200, valueGetter: ({ row }) => { const value = row?.category; return value; }, display: "flex", renderCell: function render({ value }) { return categoryLoading ? ( <>{translate("loading")} ) : ( categories?.data?.find((item) => item.id === value?.id)?.title ?? null ); }, }, { field: "price", flex: 1, headerName: translate("products.fields.price"), minWidth: 100, maxWidth: 150, display: "flex", renderCell: ({ value }) => { return ( ); }, }, { field: "actions", headerName: translate("table.actions"), sortable: false, display: "flex", renderCell: function render({ row }) { return ( <> ); }, align: "center", headerAlign: "center", minWidth: 80, }, ], [categoryLoading, categories, locale, translate], ); return ( ); }; ``` -------------------------------- ### Product Show Page with Refine MUI Source: https://refine.dev/docs/index This snippet defines the Product Show page using Refine's `Show` component and Material UI components. It displays product details, including name, price, and material. The price is formatted as currency using `NumberField`. Skeleton loaders are used for a better user experience while data is being fetched. ```tsx // file: /pages/products/show.tsx import { useOne, useShow, useTranslate } from "@refinedev/core"; import Skeleton from "@mui/material/Skeleton"; import Stack from "@mui/material/Stack"; import Typography from "@mui/material/Typography"; import { NumberField, Show, TextFieldComponent as TextField, } from "@refinedev/mui"; import type { Product } from "./types"; ``` -------------------------------- ### Refine App Configuration with MUI and React Router Source: https://refine.dev/docs/index This snippet shows the main App.tsx file for a Refine application. It configures the Refine core with data providers, router, authentication, and i18n providers. It also sets up routing for products and categories, including list, create, edit, and show views, utilizing MUI components for layout and authentication pages. ```tsx import { Authenticated, type I18nProvider, Refine } from "@refinedev/core"; import dataProvider from "@refinedev/simple-rest"; import routerProvider, { CatchAllNavigate, NavigateToResource, } from "@refinedev/react-router"; import { BrowserRouter, Outlet, Route, Routes } from "react-router"; import CssBaseline from "@mui/material/CssBaseline"; import GlobalStyles from "@mui/material/GlobalStyles"; import { AuthPage, ErrorComponent, RefineSnackbarProvider, ThemedLayout, useNotificationProvider, } from "@refinedev/mui"; import { useTranslation } from "react-i18next"; import { authProvider } from "./authProvider"; import { Header } from "./components/header"; import { ColorModeContextProvider } from "./contexts/color-mode"; import { CategoryCreate, CategoryEdit, CategoryList, CategoryShow, } from "@/pages/categories"; import { ProductCreate, ProductEdit, ProductList, ProductShow, } from "@/pages/products"; function App() { const { t, i18n } = useTranslation(); const i18nProvider: I18nProvider = { translate: (key, params) => t(key, params).toString(), changeLocale: (lang: string | undefined) => i18n.changeLanguage(lang), getLocale: () => i18n.language, }; return ( }>
}> }> } /> } /> } /> } /> } /> } /> } /> } /> } /> } /> }> }> } /> } /> ); } ``` -------------------------------- ### Product Create Form with Autocomplete Source: https://refine.dev/docs/index A form for creating a new product using Refine and React Hook Form. It includes fields for product name and description, and an autocomplete field for selecting a category. The component uses `useForm` for form state management and `useAutocomplete` for category suggestions. ```tsx // file: /pages/products/create.tsx import { type HttpError, useTranslate } from "@refinedev/core"; import { useForm } from "@refinedev/react-hook-form"; import { Controller } from "react-hook-form"; import { Autocomplete, Box, TextField } from "@mui/material"; import { Create, useAutocomplete } from "@refinedev/mui"; import type { Product } from "./types"; export const ProductCreate: React.FC = () => { const translate = useTranslate(); const { saveButtonProps, refineCore: { formLoading }, register, control, formState: { errors }, } = useForm(); const { autocompleteProps: categoryAutocompleteProps } = useAutocomplete({ resource: "categories", }); return ( {errors?.name?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("products.fields.name")} name="name" /> void; }; export const ColorModeContext = createContext( {} as ColorModeContextType, ); export const ColorModeContextProvider: React.FC = ({ children, }) => { const colorModeFromLocalStorage = localStorage.getItem("colorMode"); const isSystemPreferenceDark = window?.matchMedia( "(prefers-color-scheme: dark)", ).matches; const systemPreference = isSystemPreferenceDark ? "dark" : "light"; const [mode, setMode] = useState( colorModeFromLocalStorage || systemPreference, ); useEffect(() => { window.localStorage.setItem("colorMode", mode); }, [mode]); const setColorMode = () => { if (mode === "light") { setMode("dark"); } else { setMode("light"); } }; return ( {children} ); }; ``` -------------------------------- ### Display Product Details in React with Refine Source: https://refine.dev/docs/index This React component uses the Refine framework to display product details. It fetches product data and its associated category, handling loading and error states with skeleton loaders. Dependencies include React, Refine hooks (useTranslate, useShow, useOne), and Material UI components. ```javascript export const ProductShow: React.FC = () => { const translate = useTranslate(); const { result: product, query: { isLoading }, } = useShow(); const { data: categories, isLoading: categoryLoading, isError: categoryError, } = useOne({ resource: "categories", id: product?.category?.id, queryOptions: { enabled: !!product?.category?.id, }, }); return ( {translate("products.fields.id")} {product ? ( ) : ( )} {translate("products.fields.name")} {product ? ( ) : ( )} {translate("products.fields.description")} {product ? ( ) : ( )} {translate("products.fields.price")} {product ? ( ) : ( )} {translate("products.fields.material")} {product ? ( ) : ( )} {translate("products.fields.category")} {categoryError ? null : categoryLoading ? ( ) : ( )} ); }; ``` -------------------------------- ### Define Product Interface for Refine Source: https://refine.dev/docs/index This TypeScript file defines the 'Product' interface, specifying the structure of product data used within the Refine application. It includes fields for ID, name, description, price, material, and an optional category object. ```typescript export interface Product { id: string; name: string; description: string; price: number; material: string; category?: { id: string; } | null; } ``` -------------------------------- ### Create/Edit Product Form with Refine and Material UI Source: https://refine.dev/docs/index This snippet defines a form for creating or editing product details using Refine's `Edit` component and Material UI's `TextField` and `Autocomplete` components. It handles form state management with `react-hook-form` and includes validation for required fields. The form allows users to input product name, price, material, and select a category. ```tsx import { Controller, useFormContext, } from "react-hook-form"; import { Box, TextField as MuiTextField, Autocomplete as MuiAutocomplete, } from "@mui/material"; import { Edit, useTranslate, useResource, useParsed, } from "@refinedev/core"; import { TextField, NumberField, Autocomplete, } from "@refinedev/mui"; export const ProductEdit = () => { const translate = useTranslate(); const { resource, id } = useParsed(); const { control, formState: { errors } } = useFormContext(); const { data: productsData } = useResource({ resource: "products", id, queryOptions: { enabled: id !== undefined, }, }); const { data: categories } = useResource({ resource: "categories", queryOptions: { enabled: id !== undefined, }, }); const categoryAutocompleteProps = { options: categories?.data ?? [], loading: !categories, }; return ( {errors?.name?.message}} label={translate("products.fields.name")} margin="normal" fullWidth autoComplete="off" /> {errors?.price?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="number" label={translate("products.fields.price")} name="price" /> {errors?.material?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("products.fields.material")} name="material" /> ( { field.onChange(value); }} getOptionLabel={(item) => { return ( categoryAutocompleteProps?.options?.find( (p) => p?.id?.toString() === item?.id?.toString(), )?.title ?? "" ); }} isOptionEqualToValue={(option, value) => option?.id === value?.id} renderInput={(params) => ( )} /> )} /> ); }; ``` -------------------------------- ### Refine Header Component with Theming and Localization (TypeScript) Source: https://refine.dev/docs/index A Refine MUI themed layout header component that includes functionality for toggling dark/light mode using the ColorModeContext and switching application locale using Refine's useSetLocale and useGetLocale hooks. It also displays user identity information. ```typescript import DarkModeOutlined from "@mui/icons-material/DarkModeOutlined"; import LightModeOutlined from "@mui/icons-material/LightModeOutlined"; import { FormControl, MenuItem, Select } from "@mui/material"; import AppBar from "@mui/material/AppBar"; import Avatar from "@mui/material/Avatar"; import IconButton from "@mui/material/IconButton"; import Stack from "@mui/material/Stack"; import Toolbar from "@mui/material/Toolbar"; import Typography from "@mui/material/Typography"; import { useGetIdentity, useGetLocale, useSetLocale } from "@refinedev/core"; import { HamburgerMenu, type RefineThemedLayoutHeaderProps, } from "@refinedev/mui"; import i18n from "i18next"; import type React from "react"; import { useContext } from "react"; import { ColorModeContext } from "../../contexts/color-mode"; type IUser = { id: number; name: string; avatar: string; }; export const Header: React.FC = ({ sticky = true, }) => { const { mode, setMode } = useContext(ColorModeContext); const { data: user } = useGetIdentity(); const changeLanguage = useSetLocale(); const locale = useGetLocale(); const currentLocale = locale(); return ( ``` -------------------------------- ### Refine Authentication Provider (TypeScript) Source: https://refine.dev/docs/index Implements the Refine AuthProvider interface for handling user authentication, including login, logout, checking authentication status, and managing user identity. It uses localStorage for token storage and provides basic error handling and password reset functionalities. ```typescript import type { AuthProvider } from "@refinedev/core"; export const TOKEN_KEY = "refine-auth"; export const authProvider: AuthProvider = { login: async ({ username, email, password }) => { if ((username || email) && password) { localStorage.setItem(TOKEN_KEY, username); return { success: true, redirectTo: "/", }; } return { success: false, error: { name: "LoginError", message: "Invalid username or password", }, }; }, logout: async () => { localStorage.removeItem(TOKEN_KEY); return { success: true, redirectTo: "/login", }; }, check: async () => { const token = localStorage.getItem(TOKEN_KEY); if (token) { return { authenticated: true, }; } return { authenticated: false, redirectTo: "/login", }; }, getPermissions: async () => null, getIdentity: async () => { const token = localStorage.getItem(TOKEN_KEY); if (token) { return { id: 1, name: "John Doe", avatar: "https://i.pravatar.cc/300", }; } return null; }, onError: async (error) => { console.error(error); return { error }; }, forgotPassword: async (params) => { return { success: true, redirectTo: "/update-password", successNotification: { message: "Email has been sent.", }, }; }, updatePassword: async (params) => { return { success: true, redirectTo: "/login", successNotification: { message: "Successfully updated password.", }, }; }, }; ``` -------------------------------- ### Category Show Component using Refine Source: https://refine.dev/docs/index Displays the details of a single category using Refine's Show component. It fetches category data using `useShow` and displays the ID and title. Skeleton loaders are used while the data is loading. It leverages Material UI components for rendering. ```tsx // file: /pages/categories/show.tsx import { useShow, useTranslate, } from "@refinedev/core"; import Skeleton from "@mui/material/Skeleton"; import Stack from "@mui/material/Stack"; import Typography from "@mui/material/Typography"; import { NumberField, Show, TextFieldComponent as TextField, } from "@refinedev/mui"; import type { Category } from "./types"; export const CategoryShow = () => { const translate = useTranslate(); const { result: category, query: { isLoading }, } = useShow(); return ( {translate("categories.fields.id")} {category ? ( ) : ( )} {translate("categories.fields.title")} {category ? ( ) : ( )} ); }; ``` -------------------------------- ### Configure Authentication Routes with React Router Source: https://refine.dev/docs/index This snippet demonstrates how to configure routes for 'forgot-password' and 'update-password' using React Router within a Refine application. It utilizes the AuthPage component, passing a 'type' prop to differentiate authentication flows. No external dependencies are required beyond React Router and Refine. ```javascript import React from "react"; import { BrowserRouter, Routes, Route, } from "react-router-dom"; import { Refine, AuthPage, RefineSnackbarProvider, } from "@pankod/refine-react-router-v6"; import { ColorModeContextProvider, } from "./context/color-mode"; function App() { return ( } /> } /> ); } export default App; ``` -------------------------------- ### Category List Component using Refine and DataGrid Source: https://refine.dev/docs/index Renders a list of categories using Refine's List component and Material UI's DataGrid. It defines columns for category title and actions (Show, Edit, Delete buttons). The component utilizes `useTranslate` for localization and `useDataGrid` for data fetching and management. ```tsx // file: /pages/categories/list.tsx import { useMemo } from "react"; import { useTranslate } from "@refinedev/core"; import { DataGrid, type GridColDef } from "@mui/x-data-grid"; import { DeleteButton, EditButton, List, ShowButton, useDataGrid, } from "@refinedev/mui"; export const CategoryList: React.FC = () => { const translate = useTranslate(); const { dataGridProps } = useDataGrid(); const columns = useMemo( () => [ { field: "title", flex: 1, headerName: translate("categories.fields.title"), minWidth: 200, }, { field: "actions", headerName: translate("table.actions"), sortable: false, display: "flex", renderCell: function render({ row }) { return ( <> ); }, align: "center", headerAlign: "center", minWidth: 80, }, ], [translate], ); return ( ); }; ``` -------------------------------- ### Refine MUI Toolbar Component Source: https://refine.dev/docs/index A React component for a toolbar within a Refine MUI application. It includes navigation elements like a hamburger menu, locale selection, theme mode toggle, and user profile display. It utilizes Material UI components for layout and styling. ```jsx { setMode(); }} > {mode === "dark" ? : } {(user?.avatar || user?.name) && ( {user?.name && ( {user?.name} )} )} ``` -------------------------------- ### Product Edit Form Component (TypeScript) Source: https://refine.dev/docs/index The `ProductEdit` component is responsible for rendering the form to edit product details. It uses `useForm` from `@refinedev/react-hook-form` for form state management and validation, and `useAutocomplete` for fetching category options. The form includes fields for ID, name, description, price, material, and category, with appropriate validation and UI elements from Material UI and Refine. ```typescript import { type HttpError, useTranslate, } from "@refinedev/core"; import { useForm } from "@refinedev/react-hook-form"; import { Controller } from "react-hook-form"; import { Autocomplete, Box, TextField } from "@mui/material"; import { Edit, useAutocomplete } from "@refinedev/mui"; import type { Product } from "./types"; export const ProductEdit = () => { const translate = useTranslate(); const { saveButtonProps, refineCore: { query, formLoading }, register, control, formState: { errors }, } = useForm(); const productsData = query?.data?.data; const { autocompleteProps: categoryAutocompleteProps } = useAutocomplete({ resource: "categories", defaultValue: productsData?.category?.id, }); return ( {errors?.name?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("products.fields.name")} name="name" /> {errors?.description?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} multiline label={translate("products.fields.description")} name="description" /> {errors?.price?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="number" label={translate("products.fields.price")} name="price" /> {errors?.material?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("products.fields.material")} name="material" /> ( { field.onChange(value); }} getOptionLabel={(item) => { return ( categoryAutocompleteProps?.options?.find( (p) => p?.id?.toString() === item?.id?.toString(), )?.title ?? "" ); }} isOptionEqualToValue={(option, value) => option?.id === value?.id} renderInput={(params) => ( {errors?.category?.message}} required /> )} /> )} /> ); }; ``` -------------------------------- ### Refine React Hook Form for Category Creation Source: https://refine.dev/docs/index A React component for creating a new category using Refine's useForm hook and Material UI components. It handles form state, validation, and submission, with a single text field for the category title. ```tsx // file: /pages/categories/create.tsx import { type HttpError, useTranslate } from "@refinedev/core"; import { useForm } from "@refinedev/react-hook-form"; import { Box, TextField } from "@mui/material"; import { Create } from "@refinedev/mui"; import type { Category } from "./types"; export const CategoryCreate: React.FC = () => { const translate = useTranslate(); const { saveButtonProps, refineCore: { formLoading }, register, formState: { errors }, } = useForm(); return ( {errors?.title?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("categories.fields.title")} name="title" /> ); }; ``` -------------------------------- ### Refine React Hook Form for Category Editing Source: https://refine.dev/docs/index A React component for editing an existing category using Refine's useForm hook and Material UI components. It mirrors the creation form, providing fields for editing category details. ```tsx // file: /pages/categories/edit.tsx import { type HttpError, useTranslate } from "@refinedev/core"; import { useForm } from "@refinedev/react-hook-form"; import { Box, TextField } from "@mui/material"; import { Edit } from "@refinedev/mui"; import type { Category } from "./types"; export const CategoryEdit: React.FC = () => { const translate = useTranslate(); const { saveButtonProps, register, formState: { errors }, } = useForm(); return ( {errors?.title?.message}} margin="normal" fullWidth slotProps={{ inputLabel: { shrink: true, }, }} type="text" label={translate("categories.fields.title")} name="title" /> ); }; ``` -------------------------------- ### Category Interface Definition Source: https://refine.dev/docs/index Defines the TypeScript interface for a Category object, specifying its properties as 'id' and 'title', both of which are strings. This interface is used for type safety in the application. ```ts // file: /pages/categories/types.ts export interface Category { id: string; title: string; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.