# RSuite Documentation for LLMs This file contains the complete documentation for RSuite (React Suite), a comprehensive React component library. Generated on: 2025-11-21T04:10:20.368Z RSuite Version: 6.0.0 Source: https://github.com/rsuite/rsuite Documentation: https://rsuitejs.com/ ## About RSuite RSuite is a set of React components committed to providing high-quality and comprehensive React components to help developers quickly build web applications. ## Documentation Structure This file contains: - **Guide Documentation**: Getting started guides, usage instructions, and best practices - **Component Documentation**: For each component, includes: - Main documentation with component introduction and Props reference - Usage examples and code fragments demonstrating different features For each component, you'll find the main documentation with all examples, code fragments, and type definitions included inline, providing a complete reference in a single section. --- ================================================================================ # Components: Accordion - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/accordion/en-US/index.md ================================================================================ # Accordion The Accordion component is used to expand and collapse the content area by clicking the title. It is often used to display a large amount of content in a limited space. ## Import **Main import:** ```js import { Accordion } from 'rsuite'; ``` **Individual import:** ```js import Accordion from 'rsuite/Accordion'; // (Optional) Import component styles. import 'rsuite/Accordion/styles/index.css'; ``` ## Examples ### Basic By default, multiple panels can be expanded. Click the title to expand or collapse the accordion panel area. ```js import { Accordion, Placeholder } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Bordered ```js import { Accordion, Placeholder } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Expand only one panel When `defaultActiveKey` or `activeKey` is set, only one panel can be expanded. ```js import { Accordion, Placeholder } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled `activeKey` can be controlled by `onSelect` callback. ```js import { Accordion, Placeholder, ButtonGroup, Button } from 'rsuite'; const App = () => { const [activeKey, setActiveKey] = React.useState(1); return ( <> {[1, 2, 3].map(key => ( ))}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom Indicator ```js import { Accordion, Placeholder } from 'rsuite'; import { FaAngleDoubleDown, FaArrowAltCircleDown, FaArrowDown } from 'react-icons/fa'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom Header ```jsx import { Accordion, Placeholder, Stack, Avatar } from 'rsuite'; const Header = props => { const { avatarUrl, title, subtitle, ...rest } = props; return (
{title}
{subtitle}
); }; const App = () => ( } eventKey={1} > React is a JavaScript library for building user interfaces.

Declarative: React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable, simpler to understand, and easier to debug.

Component-Based: Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep the state out of the DOM.

Learn Once, Write Anywhere: We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using React Native.

} eventKey={2} > Vue (pronounced /vjuː/, like view) is a JavaScript framework for building user interfaces. It builds on top of standard HTML, CSS, and JavaScript and provides a declarative and component-based programming model that helps you efficiently develop user interfaces, be they simple or complex. } eventKey={3} > Angular is a web framework that empowers developers to build fast, reliable applications. Maintained by a dedicated team at Google, Angular provides a broad suite of tools, APIs, and libraries to simplify and streamline your development workflow. Angular gives you a solid platform on which to build fast, reliable applications that scale with both the size of your team and the size of your codebase.
); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled Panel ```js import { Accordion, Placeholder } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - `aria-expanded`: Indicates whether the panel is expanded or collapsed. - `aria-controls`: Identifies the content that is controlled by the panel. - `aria-labelledby`: Identifies the element that serves as the title for the panel. - `aria-disabled`: Indicates that the panel is disabled. ### Keyboard interactions - Tab: Move focus to the next focusable panel. - Enter or Space: Expand or collapse the panel. ### Resources - [ARIA Practices: Accordion Pattern](https://www.w3.org/WAI/ARIA/apg/patterns/accordion/) ## Props ### `` | Property | Type `(Default)` | Description | | ---------------- | --------------------------------- | -------------------------------------------- | | activeKey | string | The active item's event key. | | bordered | boolean | Show border. | | classPrefix | string | The prefix of the component CSS class. | | defaultActiveKey | string | The default active item's event key. | | onSelect | (eventKey: string, event) => void | Callback fired when the active item changes. | ### `` | Property | Type `(Default)` | Description | | --------------- | ------------------ | ----------------------------------------- | | bodyFill | boolean | Content area filled with containers. | | caretAs | ReactNode | Custom indicator. | | classPrefix | string `('panel')` | The prefix of the component CSS class. | | defaultExpanded | boolean | Expand the panel by default. | | disabled | boolean | Disable the panel. | | eventKey | string | The event key corresponding to the panel. | | expanded | boolean | Expand the panel. | | header | ReactNode | The title of the panel. | ================================================================================ # Components: Affix - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/affix/en-US/index.md ================================================================================ # Affix Components such as navigation, buttons, etc. can be fixed in the visible range. Commonly used for pages with long content, fixed the specified elements in the visible range of the page to assist in quick operation. ## Import **Main import:** ```js import { Affix } from 'rsuite'; ``` **Individual import:** ```js import Affix from 'rsuite/Affix'; ``` ## Examples ### Basic ```js import { Affix, Button, Placeholder } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Top ```js import { Affix, Button, Placeholder } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Container When the container is in the visible range, the element is fixed. When the scrolling page container is not in the visible range, the element is unfixed. ```js import { Affix, Button, Placeholder } from 'rsuite'; const App = () => { const container = React.useRef(); return ( <>
{ return container.current; }} >
); }; ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type`(Default)` | Description | | ----------- | ---------------------------------- | ----------------------------------------------------------------------------------------------- | | children | ReactNode | Fixed element. | | classPrefix | string `('affix')` | The prefix of the component CSS class. | | container | HTMLElement \| (() => HTMLElement) | Specify the container. An element can only be fixed when the container is in the visible range. | | onChange | (fixed: boolean) => voide | Callback function when non-fixed and fixed state changes. | | top | number `(0)` | Set the fixed top height. | ================================================================================ # Components: Animation - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/animation/en-US/index.md ================================================================================ # Animation `Animation` component is a set of animation components. You can achieve animation effects by configuring related properties. ## Import **Main import:** ```js import { Animation } from 'rsuite'; ``` **Individual import:** ```js import Animation from 'rsuite/Animation'; // (Optional) Import component styles. import 'rsuite/Animation/styles/index.css'; ``` - `Animation.Fade` Fade animation. - `Animation.Collapse` Collapse animation. - `Animation.Bounce` Bounce animation. - `Animation.Slide` Slide animation. - `Animation.Transition` Custom animation. ## Examples ### Fade ```js import { Animation, Button, Card } from 'rsuite'; const AnimatedPanel = React.forwardRef((props, ref) => (
Fade Animation This panel demonstrates a smooth fade transition effect.
)); const App = () => { const [show, setShow] = React.useState(true); const onChange = () => setShow(!show); return (

{(props, ref) => }
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Collapse ```js import { Animation, Button, Card } from 'rsuite'; const AnimatedPanel = React.forwardRef((props, ref) => (
Collapse Animation Demonstrates vertical and horizontal collapse transitions.
)); const App = () => { const [show, setShow] = React.useState(true); const onChange = () => setShow(!show); return (

Vertical Collapse {(props, ref) => } Horizontal Collapse {(props, ref) => }
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Bounce ```js import { Animation, Button, Card } from 'rsuite'; const AnimatedPanel = React.forwardRef((props, ref) => (
Bounce Animation This is a beautiful animated panel that demonstrates the bounce effect.
)); const App = () => { const [show, setShow] = React.useState(true); const onChange = () => setShow(!show); return (

{(props, ref) => }
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Slide ```js import { Animation, Button, ButtonToolbar, Card } from 'rsuite'; const AnimatedPanel = React.forwardRef((props, ref) => (
Slide Animation This panel demonstrates sliding transitions from different directions.
)); const App = () => { const [show, setShow] = React.useState(true); const [placement, setPlacement] = React.useState('right'); const onChange = placement => { setShow(!show); setPlacement(placement); }; return (

{(props, ref) => }
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Transition Configure the following className in Transition and customize the related css animation. ``` exitedClassName="custom-exited" exitingClassName="custom-exiting" enteredClassName="custom-entered" enteringClassName="custom-entering" ``` ```js import { Animation, Button, ButtonToolbar, Card } from 'rsuite'; const AnimatedPanel = React.forwardRef(({ ...props }, ref) => (
Custom Transition Click different buttons to see various animation effects!
)); const App = () => { const [show, setShow] = React.useState(true); const [effect, setEffect] = React.useState('zoom'); const onChange = newEffect => { setShow(!show); setEffect(newEffect); }; return (

{(props, ref) => }
); }; function Styles() { return ( ); } ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type `(Default)` | Description | | ----------------- | ------------------------------------ | ----------------------------------------------------------------- | | enteredClassName | string | Adding a className after the component finished transtioning in | | enteringClassName | string | Adding a className as the component begins to transition in | | exitedClassName | string | Adding a className after the component finishes transitioning out | | exitingClassName | string | Adding a className as the component begins to transition out | | in | boolean | When true The animation will show itself | | onEnter | (node?: null, Element, Text) => void | Callback fired before the component transitions in | | onEntered | (node?: null, Element, Text) => void | Callback fired after the component finishes transitioning in | | onEntering | (node?: null, Element, Text) => void | Callback fired as the component begins to transition in | | onExit | (node?: null, Element, Text) => void | Callback fired right before the component transitions out | | onExited | (node?: null, Element, Text) => void | Callback fired after the Modal finishes transitioning out | | onExiting | (node?: null, Element, Text) => void | Callback fired as the component begins to transition out | | timeout | number `(300)` | Animation transition delay time | | transitionAppear | boolean | Turn on transitions when initially displayed | | unmountOnExit | boolean | Unmount component on exit | ### `` | Property | Type `(Default)` | Description | | ----------------- | -------------------------------------------------------- | ----------------------------------------------------------------- | | dimension | 'height'|'width'|() => ('height'|'width') | Set fold size type | | enteredClassName | string `('collapse in')` | Adding a className after the component finished transtioning in | | enteringClassName | string `('collapsing')` | Adding a className as the component begins to transition in | | exitedClassName | string `('collapse')` | Adding a className after the component finishes transitioning out | | exitingClassName | string `('collapsing')` | Adding a className as the component begins to transition out | | getDimensionValue | () => number | Custom size value | | in | boolean | When true The animation will show itself | | onEnter | (node?: null, Element, Text) => void | Callback fired before the component transitions in | | onEntered | (node?: null, Element, Text) => void | Callback fired after the component finishes transitioning in | | onEntering | (node?: null, Element, Text) => void | Callback fired as the component begins to transition in | | onExit | (node?: null, Element, Text) => void | Callback fired right before the component transitions out | | onExited | (node?: null, Element, Text) => void | Callback fired after the Modal finishes transitioning out | | onExiting | (node?: null, Element, Text) => void | Callback fired as the component begins to transition out | | role | string | HTML role | | timeout | number`(300)` | Animation transition delay time | | transitionAppear | boolean | Turn on transitions when initially displayed | | unmountOnExit | boolean | Unmount component on exit | ### `` | Property | Type `(Default)` | Description | | ----------------- | ------------------------------------ | ----------------------------------------------------------------- | | enteredClassName | string | Adding a className after the component finished transtioning in | | enteringClassName | string | Adding a className as the component begins to transition in | | exitedClassName | string | Adding a className after the component finishes transitioning out | | exitingClassName | string | Adding a className as the component begins to transition out | | in | boolean | When true The animation will show itself | | onEnter | (node?: null, Element, Text) => void | Callback fired before the component transitions in | | onEntered | (node?: null, Element, Text) => void | Callback fired after the component finishes transitioning in | | onEntering | (node?: null, Element, Text) => void | Callback fired as the component begins to transition in | | onExit | (node?: null, Element, Text) => void | Callback fired right before the component transitions out | | onExited | (node?: null, Element, Text) => void | Callback fired after the Modal finishes transitioning out | | onExiting | (node?: null, Element, Text) => void | Callback fired as the component begins to transition out | | timeout | number `(300)` | Animation transition delay time | | transitionAppear | boolean | Turn on transitions when initially displayed | | unmountOnExit | boolean | Unmount component on exit | ### `` | Property | Type `(Default)` | Description | | ----------------- | ------------------------------------ | ----------------------------------------------------------------- | | enteredClassName | string | Adding a className after the component finished transtioning in | | enteringClassName | string | Adding a className as the component begins to transition in | | exitedClassName | string | Adding a className after the component finishes transitioning out | | exitingClassName | string | Adding a className as the component begins to transition out | | in | boolean | When true The animation will show itself | | onEnter | (node?: null, Element, Text) => void | Callback fired before the component transitions in | | onEntered | (node?: null, Element, Text) => void | Callback fired after the component finishes transitioning in | | onEntering | (node?: null, Element, Text) => void | Callback fired as the component begins to transition in | | onExit | (node?: null, Element, Text) => void | Callback fired right before the component transitions out | | onExited | (node?: null, Element, Text) => void | Callback fired after the Modal finishes transitioning out | | onExiting | (node?: null, Element, Text) => void | Callback fired as the component begins to transition out | | timeout | number `(300)` | Animation transition delay time | | transitionAppear | boolean | Turn on transitions when initially displayed | | unmountOnExit | boolean | Unmount component on exit | | placement | Placement `('right')` | The placement of component | ### `` | Property | Type `(Default)` | Description | | ----------------- | ------------------------------------ | ----------------------------------------------------------------- | | enteredClassName | string | Adding a className after the component finished transtioning in | | enteringClassName | string | Adding a className as the component begins to transition in | | exitedClassName | string | Adding a className after the component finishes transitioning out | | exitingClassName | string | Adding a className as the component begins to transition out | | in | boolean | When true The animation will show itself. | | onEnter | (node?: null, Element, Text) => void | Callback fired before the component transitions in | | onEntered | (node?: null, Element, Text) => void | Callback fired after the component finishes transitioning in | | onEntering | (node?: null, Element, Text) => void | Callback fired as the component begins to transition in | | onExit | (node?: null, Element, Text) => void | Callback fired right before the component transitions out | | onExited | (node?: null, Element, Text) => void | Callback fired after the Modal finishes transitioning out | | onExiting | (node?: null, Element, Text) => void | Callback fired as the component begins to transition out | | timeout | number`(1000)` | Animation transition delay time | | transitionAppear | boolean | Turn on transitions when initially displayed | | unmountOnExit | boolean | Unmount component on exit | #### `ts:Placement` ```ts type Placement = 'top' | 'bottom' | 'right' | 'left'; ``` ================================================================================ # Components: Auto Complete - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/auto-complete/en-US/index.md ================================================================================ # AutoComplete Provide auto-complete functionality for input box. ## Import **Main import:** ```js import { AutoComplete } from 'rsuite'; ``` **Individual import:** ```js import AutoComplete from 'rsuite/AutoComplete'; // (Optional) Import component styles. import 'rsuite/AutoComplete/styles/index.css'; ``` ## Examples ### Basic ```js import { AutoComplete } from 'rsuite'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ]; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Autocomplete suffix ```js import { AutoComplete } from 'rsuite'; const suffixes = ['@gmail.com', '@sina.com.cn', '@163.com', '@qq.com']; const App = () => { const [data, setData] = React.useState([]); const handleChange = value => { const at = value.match(/@[\S]*/); const nextData = at ? suffixes .filter(item => item.indexOf(at[0]) >= 0) .map(item => { return `${value}${item.replace(at[0], '')}`; }) : suffixes.map(item => `${value}${item}`); setData(nextData); }; return ; }; ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { AutoComplete, VStack } from 'rsuite'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ]; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom Render Item ```js import { AutoComplete } from 'rsuite'; import MemberIcon from '@rsuite/icons/Member'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ]; const App = () => ( { return (
{item}
); }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { AutoComplete, VStack, HStack, Text, Divider } from 'rsuite'; const data = []; const App = () => ( }> Disabled ReadOnly Plaintext ); ReactDOM.render(, document.getElementById('root')); ``` ### Combined with InputGroup ```js import { AutoComplete, InputGroup, VStack } from 'rsuite'; import SearchIcon from '@rsuite/icons/Search'; import MemberIcon from '@rsuite/icons/Member'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ]; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled ```js import { AutoComplete } from 'rsuite'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ]; const App = () => { const [value, setValue] = React.useState(''); return ; }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - Autocomplete has role `combobox`. - Has the `aria-haspopup="listbox"` attribute to indicate that the input has a popup listbox. - Has the `aria-expanded` attribute to indicate whether the listbox is open or not. - Has the `aria-controls` attribute to indicate the ID of the listbox element. - Has the `aria-activedescendant` attribute to indicate the ID of the focused option. ### Keyboard interactions - Down - Move focus to the next option. - Up - Move focus to the previous option. - Enter - Select the focused option. - Esc - Close the listbox. ## Props ### `` | Property | Type`(Default)` | Description | | -------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | | classPrefix | string `('auto-complete')` | The prefix of the component CSS class | | data \* | [Option](#code-ts-item-data-type-code)[] \| string[] | The data of component | | defaultValue | string | The default value (uncontrolled) | | disabled | boolean | Whether disabled select | | filterBy | (value: string, item: [Option](#code-ts-item-data-type-code)) => boolean | Custom filter rules (will only display items that value is a substring of which by default) | | onChange | (value:string, event) => void | Called when select an option or input value change, or value of input is changed | | onClose | () => void | Callback fired when hidden | | onEnter | () => void | Callback fired before the overlay transitions in | | onEntered | () => void | Callback fired after the overlay finishes transitioning in | | onEntering | () => void | Callback fired as the overlay begins to transition in | | onExit | () => void | Callback fired right before the overlay transitions out | | onExited | () => void | Callback fired after the overlay finishes transitioning out | | onExiting | () => void | Callback fired as the overlay begins to transition out | | onSelect | (item: [Option](#code-ts-item-data-type-code), event) => void | Called when a option is selected. | | placeholder | ReactNode | The placeholder of input | | popupClassName | string | Custom class name for the popup | | popupStyle | CSSProperties | Custom style for the popup | | renderListbox | (listbox:ReactNode) => ReactNode | Custom render listbox | | renderOption | (label:ReactNode, item: [Option](#code-ts-item-data-type-code)) => ReactNode | Custom render option | | selectOnEnter | boolean `(true)` | When set to `false`, the Enter key selection function is invalid | | size | 'lg' \| 'md' \| 'sm' \| 'xs' | A component can have different sizes | | value | string | The current value (controlled) | #### `ts:Option` ```ts interface Option { /** The value of the option corresponds to the `valueKey` in the data. **/ value: V; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** * The data of the child option corresponds to the `childrenKey` in the data. * Properties owned by tree structure components, such as TreePicker, Cascader. */ children?: Option[]; /** * Properties of grouping functional components, such as CheckPicker, InputPicker */ groupBy?: string; /** * The children under the current node are loading. * Used for components that have cascading relationships and lazy loading of children. E.g. Cascader, MultiCascader */ loading?: boolean; } ``` ================================================================================ # Components: Avatar - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/avatar/en-US/index.md ================================================================================ # Avatar Used to display an avatar or brand. ## Import **Main import:** ```js import { Avatar, AvatarGroup } from 'rsuite'; ``` **Individual import:** ```js import Avatar from 'rsuite/Avatar'; import AvatarGroup from 'rsuite/AvatarGroup'; // (Optional) Import component styles. import 'rsuite/Avatar/styles/index.css'; import 'rsuite/AvatarGroup/styles/index.css'; ``` ## Examples ### Basic ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Character avatar ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( <> R X 👍
R X 👍 ); ReactDOM.render(, document.getElementById('root')); ``` ### Icon avatars ```js import { AvatarGroup, Badge, Avatar } from 'rsuite'; import { FaUserLarge } from 'react-icons/fa6'; import { FcBusinessman, FcCustomerSupport } from 'react-icons/fc'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Image avatars ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Bordered ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Color ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Avatar Fallbacks If there is an error loading the src of the avatar, there are 2 fallbacks: 1. If there is an `alt` prop, the value of the alt attribute will be rendered. 2. If there is no `alt` prop, a default avatar will be rendered. ```js import { AvatarGroup, Avatar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Stacked avatars ```js import { AvatarGroup, Avatar } from 'rsuite'; const users = [ { avatar: 'https://i.pravatar.cc/150?u=1', name: 'John Doe' }, { avatar: 'https://i.pravatar.cc/150?u=2', name: 'Tom Doe' }, { avatar: 'https://i.pravatar.cc/150?u=3', name: 'Jerry Doe' }, { avatar: 'https://i.pravatar.cc/150?u=4', name: 'Lily Doe' }, { avatar: 'https://i.pravatar.cc/150?u=5', name: 'Lucy Doe' }, { avatar: 'https://i.pravatar.cc/150?u=6', name: 'Mike Doe' }, { avatar: 'https://i.pravatar.cc/150?u=7', name: 'Jane Doe' }, { avatar: 'https://i.pravatar.cc/150?u=8', name: 'Kate Doe' }, { avatar: 'https://i.pravatar.cc/150?u=9', name: 'Jack Doe' }, { avatar: 'https://i.pravatar.cc/150?u=10', name: 'Rose Doe' } ]; const max = 4; const App = () => ( <> {users.map(user => ( ))}
{users .filter((user, i) => i < max) .map(user => ( ))} +{users.length - max} ); ReactDOM.render(, document.getElementById('root')); ``` ### With badge ```js import { AvatarGroup, Badge, Avatar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type | Description | Version | | ----------- | ----------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------- | | alt | string | This attribute defines the alternative text for the image avatar. | | | bordered | boolean | Whether to show the border. | ![][5.59.0] | | children | string \| Element | Content(It maybe text or icon). | | | circle | boolean | Render a circle avatar. | | | classPrefix | string `('avatar')` | The prefix of the component CSS class. | | | color | [ColorScheme][color-scheme] \| CSSProperties['color'] | Set the background color of the avatar. | ![][5.59.0] | | imgProps | object | Attributes applied to the `img` element if the component is used to display an image. | | | onError | (event) => void | Callback when the image fails to load. | ![][5.59.0] | | size | [Size][size] \| `('md')` | Size of avatar. | | | sizes | string | The `sizes` attribute for the `img` element. | | | src | string | The `src` attribute for the `img` element. | | | srcSet | string | The `srcSet` attribute for the `img` element. Use this attribute for responsive image display. | | ### `` | Property | Type`(Default)` | Description | | -------- | --------------- | ------------------------------- | | size | [Size][size] | Set the size of all avatars. | | spacing | number | Set the spacing of the avatars. | | stack | boolean | Render all avatars as stacks. | #### `ts:ColorScheme` ```ts type Color = 'red' | 'orange' | 'yellow' | 'green' | 'cyan' | 'blue' | 'violet'; type ShadeValue = 50 | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900; // Color with shade type (e.g., red.50, blue.500) type ColorShade = `${Colours}.${ShadeValue}` | `${ColorGray}.${ShadeValue}`; // Combined type that allows both basic colors and colors with shades type ColorScheme = Color | ColorShade; ``` #### `ts:Size` ```ts type Size = 'xs' | 'sm' | 'md' | 'lg' | 'xl'; ``` [color-scheme]: #code-ts-color-scheme-code [size]: #code-ts-size-code ================================================================================ # Components: Badge - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/badge/en-US/index.md ================================================================================ # Badge Used to display the number of unread messages or status on icons or other components. ## Usage **Main import:** ```js import { Badge } from 'rsuite'; ``` **Individual import:** ```js import Badge from 'rsuite/Badge'; // (Optional) Import component styles. import 'rsuite/Badge/styles/index.css'; ``` ## Examples ### Basic ```js import { Avatar, Badge } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### With content ```js import { Badge, Avatar, HStack } from 'rsuite'; import { MdCheck, MdNotifications, MdError } from 'react-icons/md'; import { BsExclamation } from "react-icons/bs"; const App = () => ( }> }> }> ); ReactDOM.render(, document.getElementById('root')); ``` ### Placement ```js import { Avatar, Badge, HStack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Shapes If the wrapped element is a circle, you can use the `shape` property `circle` to make the Badge position more reasonable. ```js import { Avatar, Badge, HStack, IconButton } from 'rsuite'; import { MdNotifications } from 'react-icons/md'; const App = () => ( <>
} size="sm" appearance="primary" /> } circle size="sm" appearance="primary" /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Sizes The Badge component supports different sizes through the `size` prop. ```js import { Badge, Avatar, HStack } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Offset If the Badge position is not reasonable, you can use the `offset` property to make fine adjustments. ```js import { Avatar, Badge, HStack, IconButton } from 'rsuite'; import { MdNotifications } from 'react-icons/md'; const App = () => ( } circle appearance="subtle" /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Invisible ```js import { Badge, Avatar, Toggle, HStack } from 'rsuite'; const App = () => { const [show, setShow] = React.useState(true); return ( <>
Show Badge ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Badge without children ```js import { Badge, HStack } from 'rsuite'; import { MdCheck, MdNotifications } from 'react-icons/md'; import { BsExclamation } from 'react-icons/bs'; const App = () => ( <> } /> } />
} /> Ready
} /> Error ); ReactDOM.render(, document.getElementById('root')); ``` ### Colors ```js import { Badge, Avatar, HStack } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type`(Default)` | Description | Version | | ----------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------- | ---------- | | children | ReactNode | The wrapped component | | | classPrefix | string `('badge')` | The prefix of the component CSS class | | | color | [Color](#code-ts-color-code) \| CSSProperties['color'] | Set the color of the badge | | | compact | boolean | Whether to use compact mode | ![][6.0.0] | | content | number \| ReactNode | The content of the badge | | | invisible | boolean | Whether the badge is invisible | ![][6.0.0] | | maxCount | number`(99)` | Max count number(Only valid if `content` is type number) | | | offset | [number,number] \| [string, string] | Define the horizontal and vertical offset of the badge relative to its wrapped element | ![][6.0.0] | | outline | boolean`(true)` | Whether to use outline mode | ![][6.0.0] | | placement | [PlacementCorners](#code-ts-placement-corners-code) | Set the position of the badge in the wrapped element | ![][6.0.0] | | shape | 'rectangle' \| 'circle' | The shape of the wrapped element | ![][6.0.0] | | size | 'xs' \| 'sm' \| 'md' \| 'lg' \| 'xl' `('md')` | Set the size of the badge | | #### `ts:Color` ```ts type Color = 'red' | 'orange' | 'yellow' | 'green' | 'cyan' | 'blue' | 'violet'; ``` #### `ts:PlacementCorners` ```ts type PlacementCorners = 'topStart' | 'topEnd' | 'bottomStart' | 'bottomEnd'; ``` ================================================================================ # Components: Box - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/box/en-US/index.md ================================================================================ # Box Box component is the base component for all components, providing shorthand for style properties. ## Import **Main import:** ```js import { Box } from 'rsuite'; ``` **Individual import:** ```js import Box from 'rsuite/Box'; // (Optional) Import component styles. import 'rsuite/Box/styles/index.css'; ``` ## Usage ```js const App = () => ( This is the Box ); ``` ## Examples ### Color and Background ```js import { Box, HStack, VStack } from 'rsuite'; const App = () => ( <> bg: blue.100 c: blue.600 bg: linear-gradient(45deg, #4CAF50, #2196F3) c: white ); ReactDOM.render(, document.getElementById('root')); ``` ### Border and Rounded ```js import { Box, HStack } from 'rsuite'; const App = () => ( This is the Box This is the Box ); ReactDOM.render(, document.getElementById('root')); ``` ### Shadow ```js import { Box, HStack } from 'rsuite'; const App = () => ( This is the Box This is the Box ); ReactDOM.render(, document.getElementById('root')); ``` ## Responsive Box component supports responsive values for all shorthand CSS properties. This allows you to define different styles for different breakpoints. ```jsx This box has responsive width, padding and display ``` ## Props ### `` | Property | Type`(default)` | Description | | --------- | -------------------------- | ------------------------------------------------------------------- | | as | ElementType `('div')` | Custom element type for the component | | children | ReactNode | The content of the component | | className | string | Additional CSS class | | display | CSSProperties['display'] | CSS display property | | hideFrom | [Breakpoints][breakpoints] | Breakpoint above which the component is hidden with `display: none` | | showFrom | [Breakpoints][breakpoints] | Breakpoint below which the component is hidden with `display: none` | | style | CSSProperties | Inline style | ### `Style Props` The Box component provides a series of shorthand properties for more concise style settings. These properties directly map to their corresponding CSS properties. See the [Style Props](/guide/style-props) documentation for a complete reference of style properties. - **Theme Values**: Provided theme presets, such as ``, ``, etc. - **Responsive Values**: Provided responsive values, such as ``, etc. - **CSS Native Properties**: Provided CSS native properties, such as ``, ``, etc. ### Type Definitions #### `ts:Breakpoints` ```ts type Breakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl'; ``` [breakpoints]: #code-ts-breakpoints-code ================================================================================ # Components: Breadcrumb - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/breadcrumb/en-US/index.md ================================================================================ # Breadcrumb Used to display the current page path and quickly return to the history page. ## Import **Main import:** ```js import { Breadcrumb } from 'rsuite'; ``` **Individual import:** ```js import Breadcrumb from 'rsuite/Breadcrumb'; // (Optional) Import component styles. import 'rsuite/Breadcrumb/styles/index.css'; ``` ## Examples ### Basic A basic example of breadcrumb navigation. ```js import { Breadcrumb } from 'rsuite'; const App = () => ( Home Components Breadcrumb ); ReactDOM.render(, document.getElementById('root')); ``` ### Size Breadcrumbs are available in different sizes to match your design needs. ```js import { Breadcrumb, VStack } from 'rsuite'; const BreadcrumbBox = ({ size }) => ( Home Products Electronics Smartphones {`${size}`} ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### With Icons Add icons to breadcrumb items for enhanced visual cues. ```js import { Breadcrumb } from 'rsuite'; import { GoHomeFill } from 'react-icons/go'; const App = () => ( }>Home Components Breadcrumb ); ReactDOM.render(, document.getElementById('root')); ``` ### With Background Add background color to make breadcrumbs stand out on the page. ```js import { Breadcrumb, Box } from 'rsuite'; import { GoHomeFill } from 'react-icons/go'; const App = () => ( }>Home Components Breadcrumb ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom separator Replace the default separator with custom elements or icons. ```js import Link from 'next/link'; import { Breadcrumb, VStack } from 'rsuite'; import { MdArrowRightAlt } from 'react-icons/md'; const BreadcrumbBox = ({ separator }) => ( Home Components Breadcrumb ); const App = () => ( '} /> } /> ); ReactDOM.render(, document.getElementById('root')); ``` ### With Expand Should automatically collapse if there are more than 5 items. Use `maxItems` to set the maximum number of breadcrumbs to display. ```js import { Breadcrumb } from 'rsuite'; const App = () => ( { console.log('call onExpand'); }} > Home Library Data Computer Science Programming Languages JavaScript ); ReactDOM.render(, document.getElementById('root')); ``` ### Dropdown Integrate dropdown menus with breadcrumb items for additional navigation options. ```js import ArrowDownLineIcon from '@rsuite/icons/ArrowDownLine'; import { Breadcrumb, Dropdown, HStack } from 'rsuite'; const App = () => ( Home ( Components )} > Guides Components Tools Breadcrumb ); ReactDOM.render(, document.getElementById('root')); ``` ### Routing Library The `Breadcrumb.Item` component can be used with other routing libraries (such as Next.js, React Router) through the `as` prop. See the [Composition Guide](https://rsuitejs.com/guide/composition/#react-router-dom) for details. ```js import { Breadcrumb } from 'rsuite'; import Link from 'next/link'; const App = () => ( Home Components Breadcrumb ); ReactDOM.render(, document.getElementById('root')); ``` ### Accessibility WAI-ARIA:https://www.w3.org/TR/wai-aria-practices/#breadcrumb - ` Home Components Breadcrumb ``` ## Props ### `` | Property | Type `(Default)` | Description | | ----------- | ------------------------------------------------- | -------------------------------------------------------------------------------------- | | as | ElementType `('nav')` | Custom element type for the component | | classPrefix | string `('breadcrumb')` | The prefix of the component CSS class | | locale | [BreadcrumbLocaleType](/guide/i18n/#breadcrumb) | Define localization settings to display component text in the user's regional language | | maxItems | number `(5)` | Set the maximum number of breadcrumbs to display | | onExpand | (event: MouseEvent) => void | Callback function when the ellipsis is clicked in the collapsed view | | separator | ReactNode `('/')` | Custom separator between breadcrumb items | | size | 'sm' \| 'md' \| 'lg' \| number \| string `('md')` | Set the size of breadcrumb items | ### `` | Property | Type `(Default)` | Description | | ----------- | ---------------------------- | ----------------------------------------------------------------------- | | active | boolean | Indicates if the breadcrumb item is active | | as | ElementType `('a')` | Custom element type for the component. Defaults to 'a' if 'href' is set | | classPrefix | string `('breadcrumb-item')` | The prefix of the component CSS class | | href | string | When provided, renders the breadcrumb item as an anchor element | | icon | ReactNode | Custom icon to display before the breadcrumb item text | ================================================================================ # Components: Button - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/button/en-US/index.md ================================================================================ # Button Commonly used operating buttons。 ## Import **Main import:** ```js import { Button } from 'rsuite'; ``` **Individual import:** ```js import Button from 'rsuite/Button'; // (Optional) Import component styles. import 'rsuite/Button/styles/index.css'; ``` - `Button` is the most basic element in the component, you can quickly create a styled button. ## Examples ### Basic ```js import { Button } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Appearance `appearance` property sets the button style, options includes: `default`, `primary`, `link`, `subtle`, `ghost`. ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Sizes The `size` property sets the button size, options includes: `lg`, `md`, `sm`, `xs`. ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Colors The `color` property sets the button style, Options include: `red`, `orange`, `yellow`, `green`, `cyan`, `blue`, `violet`. ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Icon before Display an icon before the text. ```js import { Button, ButtonToolbar } from 'rsuite'; import AddOutlineIcon from '@rsuite/icons/AddOutline'; import GearIcon from '@rsuite/icons/Gear'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Icon after Display an icon after the text. ```js import { Button, ButtonToolbar } from 'rsuite'; import { FaExternalLinkSquareAlt } from 'react-icons/fa'; import PageEndIcon from '@rsuite/icons/PageEnd'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Block This is generally applicable to flow layouts, or to full rows at the top and bottom of a container. ```js import { Button, IconButton, ButtonToolbar } from 'rsuite'; import AddOutlineIcon from '@rsuite/icons/AddOutline'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Active ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Toggleable The Button is `toggleable`, allowing you to switch its state between active and inactive. ```js import { Button, ButtonGroup } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Loading ```js import { Button, ButtonToolbar } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA Properties - Button has role of `button`. ### Keyboard interaction - When Button has focus, Space or Enter activates it. ## Props ### ` } /> } /> } /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Sizes Set the size for all buttons in the group with the `size` prop. ```js import { Button, VStack, ButtonGroup } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance Customize the button style using the `appearance` prop. ```js import { Button, ButtonToolbar, ButtonGroup, VStack, HStack, Text } from 'rsuite'; const ButtonGroupWithAppearance = ({ appearance }) => ( {appearance} ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Vertical Stack buttons vertically using the `vertical` prop. ```js import { Button, ButtonGroup, VStack, HStack, Text } from 'rsuite'; const ButtonGroupWithAppearance = ({ appearance }) => ( {appearance} ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Divided Add dividers between buttons with the `divided` prop. ```js import { Button, ButtonGroup, VStack, HStack } from 'rsuite'; const ButtonGroupWithAppearance = ({ appearance, vertical }) => ( ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Split Button Create a split button dropdown by combining Button and Menu components. ```js import { ButtonGroup, Button, Whisper, Popover, Menu, IconButton } from 'rsuite'; import ArrowDownIcon from '@rsuite/icons/ArrowDown'; const options = ['Create a merge commit', 'Squash and merge', 'Rebase and merge']; const App = () => { const [action, setAction] = React.useState(0); return ( { const handleSelect = eventKey => { onClose(); setAction(eventKey); console.log(eventKey); }; return ( {options.map((item, index) => ( {item} ))} ); }} > } /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Button Toolbar Group multiple button groups together using the `ButtonToolbar` component. ```js import { Button, ButtonToolbar, ButtonGroup } from 'rsuite'; import PagePreviousIcon from '@rsuite/icons/PagePrevious'; import PageNextIcon from '@rsuite/icons/PageNext'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Justified The buttons are laid out horizontally in the button set and are equally wide. ```js import { Button, ButtonGroup, VStack } from 'rsuite'; const ButtonGroupWithAppearance = ({ appearance }) => ( ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Icons Use icons within button groups for better visual hierarchy and recognition. ```js import { Button, ButtonToolbar, ButtonGroup } from 'rsuite'; import { FaItalic, FaBold, FaUnderline, FaStrikethrough, FaAlignLeft, FaAlignRight, FaAlignCenter, FaAlignJustify } from 'react-icons/fa6'; const App = () => ( } toggleable /> } toggleable /> } toggleable /> } toggleable /> } toggleable /> } toggleable /> } toggleable /> } toggleable /> ); ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA Properties - ButtonGroup has a `group` role. ## Props ### `` | Property | Type `(Default)` | Description | | ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------ | | block | boolean | Display the button group as a full-width block element spanning the entire container width | | classPrefix | string `('btn-group')` | Custom CSS class prefix for styling flexibility and theme customization | | disabled | boolean | Disable all buttons within the group | | divided | boolean | Display buttons in a divided layout | | justified | boolean | Distribute buttons evenly with equal width in horizontal layout | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | Uniform size for all buttons in the group (large/medium/small/extra-small) | | vertical | boolean | Display buttons in a vertical stacked layout | ### `` Extends the [`Stack`][stack] component. [stack]: /components/stack ================================================================================ # Components: Calendar - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/calendar/en-US/index.md ================================================================================ # Calendar A component that displays data by calendar ## Import **Main import:** ```js import { Calendar } from 'rsuite'; ``` **Individual import:** ```js import Calendar from 'rsuite/Calendar'; // (Optional) Import component styles. import 'rsuite/Calendar/styles/index.css'; ``` ## Examples ### Basic ```js import { Calendar } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Compact ```js import { Calendar, Badge, List, HStack } from 'rsuite'; function getTodoList(date) { if (!date) { return []; } const day = date.getDate(); switch (day) { case 10: return [ { time: '10:30 am', title: 'Meeting' }, { time: '12:00 pm', title: 'Lunch' } ]; case 15: return [ { time: '09:30 pm', title: 'Products Introduction Meeting' }, { time: '12:30 pm', title: 'Client entertaining' }, { time: '02:00 pm', title: 'Product design discussion' }, { time: '05:00 pm', title: 'Product test and acceptance' }, { time: '06:30 pm', title: 'Reporting' } ]; default: return []; } } function renderCell(date) { const list = getTodoList(date); if (list.length) { return ; } return null; } const App = () => { const [selectedDate, setSelectedDate] = React.useState(null); const handleSelect = date => { setSelectedDate(date); }; return ( ); }; const TodoList = ({ date }) => { const list = getTodoList(date); if (!list.length) { return null; } return ( {list.map(item => (
{item.time}
{item.title}
))}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom cell styles Use `cellClassName` function to specify the custom class name added to each cell. For example, in the following code, we specify that the `.bg-gray` class name is added on Monday, Wednesday, and Friday, so that the background color of the cells in these three columns is gray. ```js import { Calendar } from 'rsuite'; const App = () => { return ( <> (date.getDay() % 2 ? 'bg-gray' : undefined)} /> ); }; const Styles = () => { return ; }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom week ```js import { Calendar, SegmentedControl, Toggle, VStack, HStack, Divider } from 'rsuite'; const options = [ { value: 0, label: 'Sun' }, { value: 1, label: 'Mon' }, { value: 2, label: 'Tue' }, { value: 3, label: 'Wed' }, { value: 4, label: 'Thu' }, { value: 5, label: 'Fri' }, { value: 6, label: 'Sat' } ]; const App = () => { const [weekStart, setWeekStart] = React.useState(0); const [isoWeek, setIsoWeek] = React.useState(false); const [showWeekNumbers, setShowWeekNumbers] = React.useState(true); return ( } spacing={10}> ISO week Show week numbers ); }; ReactDOM.render(, document.getElementById('root')); ``` - Use `weekStart` to specify the first day of the week. If `isoWeek` is set, this property is ignored. - Use `isoWeek` to enable the [ISO 8601 standard][ISO-8601], where each calendar week begins on Monday and Sunday on the seventh day. - Use `showWeekNumbers` to display week numbers. ### Lunar ```js import { Calendar, Text, Badge, HStack, VStack } from 'rsuite'; import { HolidayUtil, Lunar, Solar } from 'lunar-typescript'; function renderCell(date) { const lunar = Lunar.fromDate(date); const jieqi = lunar.getJieQi(); const day = lunar.getDayInChinese(); return (
{jieqi || day}
); } const App = () => { const [date, setDate] = React.useState(new Date()); const lunar = Lunar.fromDate(date); const solar = Solar.fromDate(date); const holiday = HolidayUtil.getHoliday(date.getFullYear(), date.getMonth() + 1, date.getDate()); return ( } spacing={10} wrap> ); }; ReactDOM.render(, document.getElementById('root')); function DayView({ date }) { const lunar = Lunar.fromDate(date); const solar = Solar.fromDate(date); const holiday = HolidayUtil.getHoliday(date.getFullYear(), date.getMonth() + 1, date.getDate()); return ( {lunar.toString()} {holiday?.getName()} {lunar.getYearInGanZhi()}({lunar.getYearShengXiao()})年 {solar.getXingZuo()}座 {lunar.getDayYi()?.map(t => ( {t} ))} {lunar.getDayJi()?.map(t => ( {t} ))} ); } const HolidayStatus = ({ date }) => { const holiday = HolidayUtil.getHoliday(date.getFullYear(), date.getMonth() + 1, date.getDate()); const styles = { position: 'absolute', right: -6, top: -26, transform: 'scale(0.8)', padding: '0 2px' }; const work = holiday?.isWork(); return holiday ? ( ) : null; }; ``` ## Props ### `` | Property | Type | Description | Version | | ------------------ | ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------- | | bordered | boolean | Show border | | | cellClassName | (date: Date) => string \| undefined | Custom cell classes base on it's date | | | compact | boolean | Display a compact calendar | | | defaultValue | Date | The default value (uncontrolled) | | | isoWeek | boolean | [ISO 8601 standard][ISO-8601], each calendar week begins on Monday and Sunday on the seventh day | | | locale | [DateTimeFormats](/guide/i18n/#date-time-formats) | Locale configuration | | | monthDropdownProps | [MonthDropdownProps][month-dropdown-props] | Props for the month dropdown | | | onChange | (date: Date) => void | Callback fired before the value changed | | | onSelect | (date: Date) => void | Callback fired before the date selected | | | renderCell | (date: Date) => ReactNode | Custom render calendar cells | | | value | Date | The current value (controlled) | | | weekStart | 0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 `(0)` | The index of the first day of the week (0 - Sunday). If `isoWeek` is `true`, the value of `weekStart` is ignored | ![][5.62.0] | #### `ts:MonthDropdownProps` ```ts import type { FixedSizeListProps } from 'react-window'; interface MonthDropdownProps extends Partial { /** * The HTML element or React component to render as the root element of the MonthDropdown. */ as?: React.ElementType; /** * The HTML element or React component to render as each item in the MonthDropdown. */ itemAs?: React.ElementType; /** * The CSS class name to apply to each item in the MonthDropdown. */ itemClassName?: string; } ``` [month-dropdown-props]: #code-ts-month-dropdown-props-code [ISO-8601]: https://en.wikipedia.org/wiki/ISO_week_date ================================================================================ # Components: Card - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/card/en-US/index.md ================================================================================ # Card Card is a container component for displaying data, which can contain multiple child components such as images, buttons, and text. It is used to display information in a structured way. ## Import **Main import:** ```js import { Card, CardGroup } from 'rsuite'; ``` **Individual import:** ```js import Card from 'rsuite/Card'; import CardGroup from 'rsuite/CardGroup'; // (Optional) Import component styles. import 'rsuite/Card/styles/index.css'; import 'rsuite/CardGroup/styles/index.css'; ``` ## Examples ### Basic ```js import { Card, Text } from 'rsuite'; const App = () => { return ( John Doe A passionate developer with a love for learning new technologies. Enjoys building innovative solutions and solving problems. Joined in January 2023 ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Shadow ```js import { Card, Text } from 'rsuite'; const App = () => { return ( John Doe A passionate developer with a love for learning new technologies. Enjoys building innovative solutions and solving problems. Joined in January 2023 ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Hover Shadow ```js import { Card, Text } from 'rsuite'; const App = () => { return ( John Doe A passionate developer with a love for learning new technologies. Enjoys building innovative solutions and solving problems. Joined in January 2023 ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Sizes ```js import { Card, CardGroup, VStack } from 'rsuite'; const App = () => { return ( Card Header - Small This is a small card with a brief description to highlight key information or content. It can be used for various purposes like displaying details, statistics, or any relevant content. Card Header - Medium This is a medium card with a brief description to highlight key information or content. It can be used for various purposes like displaying details, statistics, or any relevant content. Card Header - Large This is a large card with a brief description to highlight key information or content. It can be used for various purposes like displaying details, statistics, or any relevant content. ); }; ReactDOM.render(, document.getElementById('root')); ``` ### With Avatar ```js import { Card, Text, Avatar, HStack } from 'rsuite'; const App = () => { return ( John Doe Software Engineer A passionate developer with a love for learning new technologies. Enjoys building innovative solutions and solving problems. Joined in January 2023 ); }; ReactDOM.render(, document.getElementById('root')); ``` ### With Image ```js import { Card, Text, Button, TagGroup, Tag } from 'rsuite'; const App = () => { return ( Shadow Shadow Meet Shadow, a spirited little explorer with a heart full of adventure! This charming pup loves to roam the fields, soaking up the sights and sounds of nature. 🐶 Dog ☀️ Sunny 🌈 Rainbow ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Horizontal ```js import { Card, Text, VStack, TagGroup, Tag } from 'rsuite'; const App = () => { return ( Shadow Cream Meet Shadow, a spirited little explorer with a heart full of adventure! This charming pup loves to roam the fields, soaking up the sights and sounds of nature. 🐶 Dog ☀️ Sunny 🌈 Rainbow ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Placeholder ```js import { Card, Placeholder } from 'rsuite'; const App = () => { return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Within Form ```js import { Card, Heading, Text, Form, Button, SelectPicker } from 'rsuite'; const App = () => { return ( Create project Fill in the form below to create a new project
console.log(formValue)}> Name Platform
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Card Group ```js import { Card, CardGroup, Text } from 'rsuite'; const items = [ { name: 'John Doe', avatar: 'https://i.pravatar.cc/150?u=9', job: 'Software Engineer', description: 'A passionate developer with a love for learning new technologies. Enjoys building innovative solutions and solving problems.', joined: 'Joined in January 2023' }, { name: 'Jane Smith', avatar: 'https://i.pravatar.cc/150?u=8', job: 'UI/UX Designer', description: 'A creative designer with a keen eye for aesthetics. Focuses on user experience and intuitive interfaces.', joined: 'Joined in March 2022' }, { name: 'Michael Johnson', avatar: 'https://i.pravatar.cc/150?u=7', job: 'Data Scientist', description: 'A data scientist who enjoys analyzing complex datasets and uncovering insights to drive business decisions.', joined: 'Joined in June 2021' }, { name: 'Emily Davis', avatar: 'https://i.pravatar.cc/150?u=6', job: 'Project Manager', description: 'A project manager with a passion for leading teams to success. Specializes in Agile methodologies and team coordination.', joined: 'Joined in August 2020' } ]; const App = () => { const [columns, setColumns] = React.useState(2); const [spacing, setSpacing] = React.useState(20); return ( <> {items.map((item, index) => ( {item.name} {item.job} {item.description} {item.joined} ))}
({ label: `${value} Columns`, value }))} value={columns} onChange={setColumns} cleanable={false} /> ({ label: `${value}px`, value }))} value={spacing} onChange={setSpacing} cleanable={false} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type`(Default)` | Description | | ----------- | -------------------- | -------------------------------------- | | as | ElementType `(div)` | HTML tag of the component | | bordered | boolean`(true)` | Whether the card has a border | | children | ReactNode | The children of the component | | classPrefix | string `('card')` | The prefix of the component class name | | direction | 'row' \| 'column' | The direction of the card | | shaded | boolean \| 'hover' | Whether there is a shadow | | size | 'sm' \| 'md' \| 'lg' | The size of the card | | width | string \| number | The width of the card | ### `` | Property | Type`(Default)` | Description | | ----------- | ------------------------ | -------------------------------------- | | as | ElementType `(div)` | HTML tag of the component | | classPrefix | string `('card-header')` | The prefix of the component class name | | children | ReactNode | The children of the component | ### `` | Property | Type`(Default)` | Description | | ----------- | ---------------------- | -------------------------------------- | | as | ElementType `(div)` | HTML tag of the component | | classPrefix | string `('card-body')` | The prefix of the component class name | | children | ReactNode | The children of the component | ### `` | Property | Type`(Default)` | Description | | ----------- | ------------------------ | -------------------------------------- | | as | ElementType `(div)` | HTML tag of the component | | classPrefix | string `('card-footer')` | The prefix of the component class name | | children | ReactNode | The children of the component | ### `` | Property | Type`(Default)` | Description | | ----------- | ----------------------- | -------------------------------------- | | as | ElementType `(div)` | HTML tag of the component | | classPrefix | string `('card-group')` | The prefix of the component class name | | children | ReactNode | The children of the component | | columns | number | The number of columns of the group | | spacing | number `(16)` | The spacing between the stats | ================================================================================ # Components: Carousel - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/carousel/en-US/index.md ================================================================================ # Carousel Display a set of elements in a carousel ## Import **Main import:** ```js import { Carousel } from 'rsuite'; ``` **Individual import:** ```js import Carousel from 'rsuite/Carousel'; // (Optional) Import component styles. import 'rsuite/Carousel/styles/index.css'; ``` ## Examples ### Basic A basic carousel containing 5 images that can be navigated using the bottom indicators. ```js import { Carousel } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled slides Control the current slide programmatically using the `activeIndex` and `onSelect` props for a fully controlled carousel. ```js import { Carousel } from 'rsuite'; const App = () => { const [activeIndex, setActiveIndex] = React.useState(2); return ( { setActiveIndex(index); }} > ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Appearance Customize the carousel's indicator position (top, bottom, left, right) and shape (dots or bars). ```js import { Carousel, SegmentedControl, Divider, Text } from 'rsuite'; function App() { const [placement, setPlacement] = React.useState('bottom'); const [shape, setShape] = React.useState('dot'); return ( <>
); } ReactDOM.render(, document.getElementById('root')); ``` ### Autoplay Enable automatic slide transitions without user interaction by setting the `autoplay` prop. ```js import { Carousel } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type `(Default)` | Description | | ------------------ | ------------------------------------------------ | ---------------------------------------------- | | activeIndex | number | Controls the current visible slide | | as | ElementType `('div')` | Custom element type | | autoplay | boolean | Automatic carousel element. | | autoplayInterval | number (`4000`) | Delay in ms until navigating to the next item. | | children | ReactNode | Carousel elements | | classPrefix | string `('carousel')` | Component CSS class prefix | | defaultActiveIndex | number (`0`) | The default initial slide | | onSelect | (index: number, event?: ChangeEvent) => void | Callback fired when the active item changes | | onSlideEnd | (index: number, event?: TransitionEvent) => void | Callback fired when a slide transition ends | | onSlideStart | (index: number, event?: ChangeEvent) => void | Callback fired when a slide transition starts | | placement | enum:'top','bottom','left','right' `('bottom')` | Button placement | | shape | enum:'dot','bar' `('dot')` | Button shape | ================================================================================ # Components: Cascade Tree - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/cascade-tree/en-US/index.md ================================================================================ # CascadeTree CascadeTree is a component that displays tree-structured data in columns. ## Import **Main import:** ```js import { CascadeTree } from 'rsuite'; ``` **Individual import:** ```js import CascadeTree from 'rsuite/CascadeTree'; // (Optional) Import component styles. import 'rsuite/CascadeTree/styles/index.css'; ``` ## Examples ### Basic ```js import { CascadeTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ( <> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom options ```js import { CascadeTree } from 'rsuite'; import AdminIcon from '@rsuite/icons/Admin'; import { mockTreeData } from './mock'; const headers = ['Job Area', 'Job Type', 'Name']; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const Column = ({ header, children }) => { return (
{header}
{children}
); }; const App = () => ( { return ( <> {label} ); }} renderColumn={(childNodes, { layer }) => { return {childNodes}; }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Async Data This tree allows the use of the `getChildren` option and the length of the children field on the node to be 0 to load children asynchronously. ```js import { CascadeTree } from 'rsuite'; import FolderFillIcon from '@rsuite/icons/FolderFill'; import PageIcon from '@rsuite/icons/Page'; import { mockAsyncData } from './mock'; const [getNodes, fetchNodes] = mockAsyncData(); const initialData = getNodes(5); const App = () => { return (
{ return fetchNodes(node.id); }} renderTreeNode={(label, item) => { return ( <> {item.children ? : } {label} ); }} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Searchable ```js import { CascadeTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ( <> ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - CascadeTree has role `tree`. - Each column has role `group`. - Each item has role `treeitem`. - Each item has `aria-setsize` equal to the number of items in the column. - Each item has `aria-level` equal to the column index. - The selected item has `aria-selected="true"`. - The disabled item has `aria-disabled="true"`. - The search input has role `searchbox`. ## Props ### `` | Property | Type`(Default)` | Description | | ------------------ | ------------------------------------------------------------------------- | ---------------------------------------------------------- | | childrenKey | string `('children')` | Set the key for children in the data structure | | classPrefix | string `('cascader-tree')` | The prefix for the component's CSS class | | columnHeight | number | Specifies the height of each column | | columnWidth | number | Specifies the width of each column | | data \* | [Option][item][] | The data to be displayed in the component | | defaultValue | string | The default value for the selected items | | disabledItemValues | string[] | An array of values for items to be disabled | | getChildren | (item: [Option][item]) => Promise<[Option][item][]> | Asynchronously loads the children of a tree node | | labelKey | string `('label')` | Specifies the key for labels in the data structure | | onChange | (value: string, event) => void | Callback triggered when the selected value changes | | onSearch | (value: string, event) => void | Callback triggered when the search value changes | | onSelect | (item: [Option][item], selectedPaths: [Option][item][], event) => void | Callback triggered when an item is selected | | renderColumn | (childNodes: ReactNode, column: { items, parentItem, layer}) => ReactNode | Custom renderer for the column list | | renderTreeNode | (node: ReactNode, item: [Option][item]) => ReactNode | Custom renderer for individual tree nodes | | searchable | boolean | Determines if the search functionality is enabled | | value | string | The current value of selected items (for controlled usage) | | valueKey | string `('value')` | Specifies the key for values in the data structure | #### `ts:Option` ```ts interface Option { /** The value of the option corresponds to the `valueKey` in the data. **/ value: V; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** * The data of the child option corresponds to the `childrenKey` in the data. * Properties owned by tree structure components, such as TreePicker, Cascader. */ children?: Option[]; /** * Properties of grouping functional components, such as CheckPicker, InputPicker */ groupBy?: string; /** * The children under the current node are loading. * Used for components that have cascading relationships and lazy loading of children. E.g. Cascader, MultiCascader */ loading?: boolean; } ``` [item]: #code-ts-option-code ================================================================================ # Components: Cascader - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/cascader/en-US/index.md ================================================================================ # Cascader The `Cascader` component displays a hierarchical list of options. ## Import **Main import:** ```js import { Cascader } from 'rsuite'; ``` **Individual import:** ```js import Cascader from 'rsuite/Cascader'; // (Optional) Import component styles. import 'rsuite/Cascader/styles/index.css'; ``` ## Examples ### Basic ```js import { Cascader, VStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { Cascader } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { Cascader, VStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Block ```js import { Cascader } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Placement and Prevent overflow ```js import { Cascader } from 'rsuite'; import { mockTreeData } from './mock'; import PlacementContainer from '@/components/PlacementContainer'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ( {({ container, placement, preventOverflow }) => ( )} ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Parent selectable ```js import { Cascader } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom options ```js import { Cascader } from 'rsuite'; import AdminIcon from '@rsuite/icons/Admin'; import { mockTreeData } from './mock'; const headers = ['Job Area', 'Job Type', 'Name']; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const Column = ({ header, children }) => { return (
{header}
{children}
); }; const App = () => ( { return ( <> {label} ); }} renderColumn={(childNodes, { layer }) => { return {childNodes}; }} renderValue={(value, activePaths, activeItemLabel) => { return activePaths.map(item => item.label).join(' > '); }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { Cascader, VStack, HStack, Divider, Text } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const Field = ({ label, children, ...rest }) => ( {label} ); const App = () => ( }> ); ReactDOM.render(, document.getElementById('root')); ``` ### Async Data This tree allows the use of the `getChildren` option and the length of the children field on the node to be 0 to load children asynchronously. ```js import { Cascader } from 'rsuite'; import FolderFillIcon from '@rsuite/icons/FolderFill'; import PageIcon from '@rsuite/icons/Page'; import { mockAsyncData } from './mock'; const [getNodes, fetchNodes] = mockAsyncData(); const initialData = getNodes(5); const App = () => { const [value, setValue] = React.useState(); return (
{ return fetchNodes(node.id); }} renderTreeNode={(label, item) => { return ( <> {item.children ? : } {label} ); }} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Controlled ```js import { Cascader } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { const [value, setValue] = React.useState('1-2-2'); return ; }; ReactDOM.render(, document.getElementById('root')); ``` ## Responsive ## Accessibility ### ARIA properties - Cascader has role `combobox`. - Has the `aria-haspopup="tree"` attribute to indicate that the combobox has a popup tree. - Has the `aria-expanded` attribute to indicate whether the tree is open or not. - Has the `aria-controls` attribute to indicate the ID of the tree element. - Has the `aria-activedescendant` attribute to indicate the ID of the focused tree node. - When `label` is set, the `aria-labelledby` attribute is added to the combobox element and the tree element and is set to the value of the `id` attribute of `label`. ### Keyboard interactions - - Move focus to the next tree node. - - Move focus to the previous tree node. - - Expand the focused tree node if it is collapsed. - - Collapse the focused tree node if it is expanded. - Enter - Select the focused tree node. - Esc - Close the tree. ## Props ### `` | Property | Type`(Default)` | Description | | ------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------- | | appearance | 'default' \| 'subtle' `('default')` | Set picker appearance | | block | boolean | Occupy the full width of the parent container | | caretAs | ElementType | Custom component for the caret icon | | childrenKey | string `('children')` | Set children key in data | | classPrefix | string `('picker')` | The prefix of the component CSS class | | cleanable | boolean `(true)` | Whether the selected value can be cleared | | columnHeight | number | Sets the height of the column | | columnWidth | number | Sets the width of the column | | container | HTMLElement \| (() => HTMLElement) | Sets the rendering container | | data \* | [Option][item][] | The data of component | | defaultValue | string | Default values of the selected items | | disabled | boolean | Whether to disable the component | | disabledItemValues | string[] | Values of disabled items | | getChildren | (item: [Option][item]) => Promise<[Option][item][]> | Asynchronously load the children of the tree node | | height | number `(320)` | The height of Dropdown | | labelKey | string `('label')` | Set label key in data | | loading | boolean `(false)` | Whether to display a loading state indicator | | locale | [PickerLocaleType](/guide/i18n/#pickers) | Locale text settings | | onChange | (value:string, event) => void | Callback fired when value changes | | onClean | (event) => void | Callback fired when value is cleared | | onClose | () => void | Callback fired when component closes | | onEnter | () => void | Callback fired before the overlay transitions in | | onEntered | () => void | Callback fired after the overlay finishes transitioning in | | onEntering | () => void | Callback fired as the overlay begins to transition in | | onExit | () => void | Callback fired right before the overlay transitions out | | onExited | () => void | Callback fired after the overlay finishes transitioning out | | onExiting | () => void | Callback fired as the overlay begins to transition out | | onOpen | () => void | Callback fired when component opens | | onSearch | (search:string, event) => void | Callback function for search | | onSelect | (item: [Option][item], selectedPaths: [Option][item][], event) => void | Callback fired when an item is selected | | open | boolean | Whether the component is open | | parentSelectable | boolean | Whether parent nodes are selectable | | placeholder | ReactNode `('Select')` | Placeholder text | | placement | [Placement](#code-ts-placement-code) `('bottomStart')` | The placement of component | | popupClassName | string | Custom CSS class for the popup | | popupStyle | CSSProperties | Custom style for the popup | | preventOverflow | boolean | Prevent floating element overflow | | renderColumn | (childNodes: ReactNode, column: { items, parentItem, layer}) => ReactNode | Custom render function for column list | | renderExtraFooter | () => ReactNode | Custom render function for extra footer | | renderSearchItem | (node: ReactNode, items: [Option][item][]) => ReactNode | Custom render function for search result items | | renderTreeNode | (node: ReactNode, item: [Option][item]) => ReactNode | Custom render function for tree nodes | | renderValue | (value: string, selectedPaths: [Option][item][], selected:ReactNode) => ReactNode | Custom render function for selected items | | searchable | boolean `(true)` | Whether the component is searchable | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | Size of the component | | toggleAs | ElementType `('a')` | Custom element for the component | | value | string | Value of the component (Controlled) | | valueKey | string `('value')` | Set value key in data | #### `ts:Option` ```ts interface Option { /** The value of the option corresponds to the `valueKey` in the data. **/ value: V; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** * The data of the child option corresponds to the `childrenKey` in the data. * Properties owned by tree structure components, such as TreePicker, Cascader. */ children?: Option[]; /** * Properties of grouping functional components, such as CheckPicker, InputPicker */ groupBy?: string; /** * The children under the current node are loading. * Used for components that have cascading relationships and lazy loading of children. E.g. Cascader, MultiCascader */ loading?: boolean; } ``` #### `ts:Placement` ```ts type Placement = 'bottomStart' | 'topStart' | 'autoVerticalStart'; ``` [item]: #code-ts-option-code ================================================================================ # Components: Center - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/center/en-US/index.md ================================================================================ # Center Center is a layout component that centers its child elements within itself. ## Import **Main import:** ```js import { Center } from 'rsuite'; ``` **Individual import:** ```js import Center from 'rsuite/Center'; // (Optional) Import component styles. import 'rsuite/Center/styles/index.css'; ``` ## Examples ### Centered Content ```js import { Center } from 'rsuite'; const App = () => (
This is centered content
); ReactDOM.render(, document.getElementById('root')); ``` ### Center with Inline ```js import { Center, Box } from 'rsuite'; import { MdEmail } from 'react-icons/md'; const App = () => (
Send email
); ReactDOM.render(, document.getElementById('root')); ``` ### Icon ```js import { Center, HStack } from 'rsuite'; import { MdEmail } from 'react-icons/md'; const App = () => (
6
); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `
` Extends the [`Box`][boxprops] component. | Property | Type`(default)` | Description | | -------- | --------------- | ----------- | | inline | boolean | Inline mode | [boxprops]: /components/box/#props ================================================================================ # Components: Check Picker - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/check-picker/en-US/index.md ================================================================================ # CheckPicker Used for multiple data selection, support grouping. ## Import **Main import:** ```js import { CheckPicker } from 'rsuite'; ``` **Individual import:** ```js import CheckPicker from 'rsuite/CheckPicker'; // (Optional) Import component styles. import 'rsuite/CheckPicker/styles/index.css'; ``` ## Examples ### Basic ```js import { CheckPicker, VStack } from 'rsuite'; const data = [ 'Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert', 'Louisa', 'Lester', 'Lola', 'Lydia', 'Hal', 'Hannah', 'Harriet', 'Hattie', 'Hazel', 'Hilda' ].map(item => ({ label: item, value: item })); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### With a label ```js import { CheckPicker } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { CheckPicker } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { CheckPicker, VStack } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Sticky Set the `sticky` property to put the selected in the options to the top. ```js import { CheckPicker } from 'rsuite'; import { mockUsers } from './mock'; /** * Data structure: * [ * { firstLetter: 'A', name: 'Alan', firstName: 'Alan' }, * { firstLetter: 'B', name: 'Benson', firstName: 'Benson' }, * ] */ const data = mockUsers(100) .map(item => { const firstLetter = item.firstName[0].toUpperCase(); return { firstLetter, ...item }; }) .sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter)); const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Block ```js import { CheckPicker } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Loading state When the picker is loading, a spinner is displayed to indicate the loading state. Clicking a loading picker won't open its options menu. ```js import { CheckPicker, VStack, SegmentedControl } from 'rsuite'; const data = []; const sizes = ['xs', 'sm', 'md', 'lg']; const App = () => { const [size, setSize] = React.useState('md'); return ( <> ({ value: item, label: item }))} value={size} onChange={size => setSize(size)} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Group ```js import { CheckPicker } from 'rsuite'; import { mockUsers } from './mock'; /** * Data structure: * [ * { firstLetter: 'A', name: 'Alan', firstName: 'Alan' }, * { firstLetter: 'B', name: 'Benson', firstName: 'Benson' }, * ] */ const data = mockUsers(100) .map(item => { const firstLetter = item.firstName[0].toUpperCase(); return { firstLetter, ...item }; }) .sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter)); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Placement and Prevent overflow ```js import { CheckPicker } from 'rsuite'; import PlacementContainer from '@/components/PlacementContainer'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd'].map(item => ({ label: item, value: item })); const App = () => { return ( {({ container, placement, preventOverflow }) => ( )} ); }; ReactDOM.render(, document.getElementById('app')); ``` ### Custom options ```js import { CheckPicker, HStack } from 'rsuite'; import { FaUserGroup, FaUser } from 'react-icons/fa6'; import { mockUsers } from './mock'; /** * Data structure: * [ * { firstLetter: 'A', name: 'Alan', firstName: 'Alan' }, * { firstLetter: 'B', name: 'Benson', firstName: 'Benson' }, * ] */ const data = mockUsers(100) .map(item => { const firstLetter = item.firstName[0].toUpperCase(); return { firstLetter, ...item }; }) .sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter)); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); const renderOption = (label, item) => { return ( {label} ); }; const renderOptionGroup = (label, item) => { return ( {label} - ({item.children.length}) ); }; const renderValue = (value, items) => { return ( Users: {value.join(' , ')} ); }; ``` ### Disabled and read only ```js import { CheckPicker, VStack, HStack, Divider, Text } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const Field = ({ label, children, ...rest }) => ( {label} ); const App = () => ( }> ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled Search ```js import { CheckPicker } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Extra footer Customize a select all function. ```js import { CheckPicker, Checkbox, Button, HStack } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const allValue = data.map(item => item.value); const App = () => { const picker = React.useRef(); const [value, setValue] = React.useState([]); const handleChange = value => { setValue(value); }; const handleCheckAll = (value, checked) => { setValue(checked ? allValue : []); }; return (
( 0 && value.length < allValue.length} checked={value.length === allValue.length} onChange={handleCheckAll} > Check all )} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Async ```js import { CheckPicker, HStack, Loader } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => { const [items, setItems] = React.useState([]); const updateData = () => { setTimeout(() => { if (items.length === 0) { setItems(data); } }, 2000); }; const renderListbox = listbox => { if (items.length === 0) { return ( ); } return listbox; }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Controlled ```js import { CheckPicker, RadioGroup, Radio } from 'rsuite'; const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice', 'Julia', 'Albert'].map( item => ({ label: item, value: item }) ); const App = () => { const [value, setValue] = React.useState([]); return ; }; ReactDOM.render(, document.getElementById('root')); ``` ### Virtualize Long Lists ```js import { CheckPicker } from 'rsuite'; const data = Array.from({ length: 10000 }).map((_, index) => { return { label: `Item ${index} is a long text, Used to test the virtualized list.`, value: `Item ${index}` }; }); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ## Responsive ## Accessibility ### ARIA properties - CheckPicker has role `combobox`. - Has the `aria-haspopup="listbox"` attribute to indicate that the combobox has a popup listbox. - Has the `aria-expanded` attribute to indicate whether the listbox is open or not. - Has the `aria-controls` attribute to indicate the ID of the listbox element. - Has the `aria-activedescendant` attribute to indicate the ID of the focused option. - When `label` is set, the `aria-labelledby` attribute is added to the combobox element and the listbox element and is set to the value of the `id` attribute of `label`. - listbox has the `aria-multiselectable=true` attribute to indicate that the listbox is multi-selectable. ### Keyboard interactions - - Move focus to the next option. - - Move focus to the previous option. - Enter - Select the focused option. - Esc - Close the listbox. ## Props ### `` | Property | Type`(Default)` | Description | | ------------------ | --------------------------------------------------------------------------------- | ----------------------------------------------------------- | | appearance | 'default' \| 'subtle' `('default')` | Set picker appearence | | block | boolean | Whether to display the component as a block | | caretAs | ElementType | Custom component for the caret icon | | classPrefix | string `('picker')` | The prefix for the component CSS class | | cleanable | boolean `(true)` | Whether the selected value can be cleared | | container | HTMLElement \| (() => HTMLElement) | Sets the rendering container | | countable | boolean `(true)` | Whether to display the count of selected items | | data \* | [Option][item][] | The data for the component | | defaultValue | [Value][value] | Default values of the selected items | | disabled | boolean | Whether the component is disabled | | disabledItemValues | [Value][value] | Values of items to be disabled | | groupBy | string | Key for grouping data items | | label | ReactNode | Label displayed at the beginning of the toggle button | | labelKey | string `('label')` | Key for the label in the data items | | listboxMaxHeight | number `(320)` | Maximum height of the listbox | | listProps | [ListProps][listprops] | Properties for virtualized lists | | loading | boolean `(false)` | Whether to display a loading state indicator | | locale | [PickerLocaleType](/guide/i18n/#pickers) | Localization settings for component text | | onChange | (value: [Value][value], event) => void | Callback fired when value changes | | onClean | (event) => void | Callback fired when value is cleared | | onClose | () => void | Callback fired when component closes | | onEnter | () => void | Callback fired before the overlay transitions in | | onEntered | () => void | Callback fired after the overlay finishes transitioning in | | onEntering | () => void | Callback fired as the overlay begins to transition in | | onExit | () => void | Callback fired right before the overlay transitions out | | onExited | () => void | Callback fired after the overlay finishes transitioning out | | onExiting | () => void | Callback fired as the overlay begins to transition out | | onGroupTitleClick | (event) => void | Callback fired when a group title is clicked | | onOpen | () => void | Callback fired when component opens | | onSearch | (search:string, event) => void | Callback fired when search is performed | | onSelect | (value: [Value][value], item: [Option][item] , event) => void | Callback fired when an item is selected | | open | boolean | Whether the component is open | | placeholder | ReactNode `('Select')` | Placeholder text | | placement | [Placement](#code-ts-placement-code)`('bottomStart')` | The placement of the component | | popupClassName | string | Custom class name for the popup | | popupStyle | CSSProperties | Custom style for the popup | | preventOverflow | boolean | Prevent floating element overflow | | renderExtraFooter | () => ReactNode | Custom render function for extra footer | | renderListbox | (listbox:ReactNode) => ReactNode | Custom render function for listbox | | renderOption | (label: ReactNode, item:[Option][item]) => ReactNode | Custom render function for options | | renderOptionGroup | (title: ReactNode, item:[Option][item]) => ReactNode | Custom render function for option groups | | renderValue | (value: [Value][value], items: [Option][item][], selected:ReactNode) => ReactNode | Custom render function for selected items | | searchable | boolean `(true)` | Whether to display search input box | | searchBy | (keyword: string, label: ReactNode, item: Option) => boolean | Custom search function | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | Size of the picker | | sort | (isGroup: boolean) => (a: any, b: any) => number | Custom sort function for options | | sticky | boolean | Whether to stick selected options at the top | | toggleAs | ElementType `('a')` | Custom element type for the component | | value | [Value][value] | Values of the selected items (Controlled) | | valueKey | string `('value')` | Key for the value in the data items | | virtualized | boolean | Whether to use virtualized list | #### `ts:Option` ```ts interface Option { /** The value of the option corresponds to the `valueKey` in the data. **/ value: V; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** * The data of the child option corresponds to the `childrenKey` in the data. * Properties owned by tree structure components, such as TreePicker, Cascader. */ children?: Option[]; /** * Properties of grouping functional components, such as CheckPicker, InputPicker */ groupBy?: string; /** * The children under the current node are loading. * Used for components that have cascading relationships and lazy loading of children. E.g. Cascader, MultiCascader */ loading?: boolean; } ``` #### `ts:Placement` ```ts type Placement = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd' | 'auto' | 'autoVerticalStart' | 'autoVerticalEnd' | 'autoHorizontalStart' | 'autoHorizontalEnd'; ``` #### `ts:ListProps` ```ts interface ListProps { /** * Size of a item in the direction being windowed. */ itemSize?: number | ((index: number) => number); /** * Scroll offset for initial render. */ initialScrollOffset?: number; /** * Called when the items rendered by the list change. */ onItemsRendered?: (props: ListOnItemsRenderedProps) => void; /** * Called when the list scroll positions changes, as a result of user scrolling or scroll-to method calls. */ onScroll?: (props: ListOnScrollProps) => void; } ``` ### `ts:Value` ```ts type Value = (string | number)[]; ``` [item]: #code-ts-option-code [value]: #code-ts-value-code [listprops]: #code-ts-list-props-code ================================================================================ # Components: Check Tree - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/check-tree/en-US/index.md ================================================================================ # CheckTree `` is used to display a tree structure data and supports Checkbox selection. ## Import **Main import:** ```js import { CheckTree } from 'rsuite'; ``` **Individual import:** ```js import CheckTree from 'rsuite/CheckTree'; // (Optional) Import component styles. import 'rsuite/CheckTree/styles/index.css'; ``` ## Examples ### Basic ```js import { CheckTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Cascade The cascade attribute can set whether or not CheckTree can consider the cascade relationship of the parent parent when selecting. The default value is true. ```js import { CheckTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { const [cascade, setCascade] = React.useState(false); return (
{ setCascade(checked); }} > Cascade
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Show Indent Lines ```js import { CheckTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ( <> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom Tree Node ```js import { CheckTree } from 'rsuite'; import PageIcon from '@rsuite/icons/Page'; import { mockTreeData } from './mock'; import { MdOutlineKeyboardArrowDown, MdOutlineKeyboardArrowRight, MdFilePresent, MdFolder } from 'react-icons/md'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const TreeNode = ({ children, ...rest }) => { return (
{children}
); }; const App = () => ( { return ( {treeNode.children ? : } {treeNode.label} ); }} renderTreeIcon={(treeNode, expanded) => { if (treeNode.children) { return expanded ? : ; } return null; }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Virtualized ```js import { CheckTree, Panel, NumberInput, Button, Stack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [10, 10, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { const listRef = React.useRef(); const [index, setIndex] = React.useState(1); const [align, setAlign] = React.useState('start'); return (

Item
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Asynchronous Loading of Child Nodes ```js import { CheckTree } from 'rsuite'; import FolderFillIcon from '@rsuite/icons/FolderFill'; import PageIcon from '@rsuite/icons/Page'; import { mockAsyncData } from './mock'; const [getNodes, fetchNodes] = mockAsyncData(); const data = getNodes(5); const TreeNode = ({ children, ...rest }) => { return (
{children}
); }; const App = () => { const [value, setValue] = React.useState([]); return ( setValue(value)} getChildren={fetchNodes} renderTreeNode={node => { return ( {node.children ? : } {node.label} ); }} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Searchable ```js import { CheckTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { return ; }; ReactDOM.render(, document.getElementById('root')); ``` ### Uncheckable Tree Node ```js import { CheckTree } from 'rsuite'; const data = [ { label: 'Node 1', value: '1' }, { label: 'Node 2', value: '2', children: [ { label: 'Node 2-1', value: '2-1', children: [ { label: 'Node 2-1-1', value: '2-1-1' }, { label: 'Node 2-1-2', value: '2-1-2' } ] }, { label: 'Node 2-2', value: '2-2' } ] } ]; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled Tree Node ```js import { CheckTree } from 'rsuite'; const data = [ { label: 'Node 1', value: '1', children: [ { label: 'Node 1-1', value: '1-1' }, { label: 'Node 1-2', value: '1-2' } ] }, { label: 'Node 2', value: '2', children: [ { label: 'Node 2-1', value: '2-1', children: [ { label: 'Node 2-1-1', value: '2-1-1' }, { label: 'Node 2-1-2', value: '2-1-2' } ] }, { label: 'Node 2-2', value: '2-2' } ] } ]; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Scroll Shadows ```js import { CheckTree } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties **tree** - CheckTree has role `tree`. - CheckTree has the `aria-multiselectable=true` attribute to indicate that the tree is multi-selectable. **treeitem** - CheckTree node has role `treeitem`. - Has the `aria-expanded` attribute to indicate whether the tree is open or not. - Has the `aria-checked` attribute to indicate whether the tree node is checked or not. - Has the `aria-level` attribute to indicate the level of the tree node. - Has the `aria-disabled` attribute to indicate whether the tree node is disabled or not. ### Keyboard interactions - - Move focus to the next tree node. - - Move focus to the previous tree node. - - Expand the focused tree node if it is collapsed. - - Collapse the focused tree node if it is expanded. - Enter - Select the focused tree node. ## Props ### `` | Property | Type `(Default)` | Description | Version | | ----------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------- | ----------- | | cascade | boolean `(true)` | Whether to enable cascade selection | | | childrenKey | string `('children')` | Set the `key` of the child node of the tree node in `data` | | | data \* | [TreeNode][node][] | Data to render the tree | | | defaultExpandAll | boolean | Default expand all nodes | | | defaultExpandItemValues | string[] | Set the value of the default expanded node | | | defaultValue | string[] | Default selected Value | | | disabledItemValues | string[] | Disabled tree node values | | | expandItemValues | string[] | Set the value of the expanded node (controlled) | | | getChildren | (item: [TreeNode][node]) => Promise<[TreeNode][node]> | Load node children data asynchronously | | | height | number `(360px)` | The height of the tree | | | labelKey | string `('label')` | Set the tree node display content to the `key` in `data` | | | listProps | [ListProps][listprops] | Properties of virtualized lists | | | onChange | (values:string[]) => void | Called when the tree value changes | | | onExpand | (expandItemValues: string[], item: [TreeNode][node], concat:(data, children) => Array) => void | Called when the tree node expands the child node | | | onSearch | (keyword: string) => void | Called when the search box changes | | | onSelect | (item: [TreeNode][node], value:string, event) => void | Called when the tree node is selected | | | renderTreeIcon | (item: [TreeNode][node], expanded: boolean) => ReactNode | Custom render the icon in tree node | | | renderTreeNode | (item: [TreeNode][node]) => ReactNode | Custom render tree node | | | scrollShadow | boolean | The shadow of the content when scrolling | ![][5.62.0] | | searchable | boolean | Whether to show the search box | ![][5.61.0] | | searchKeyword | string | Set search keywords for the search box | | | uncheckableItemValues | string[] | Set the tree node values that do not display checkboxes | | | value | string[] | The value of the selected tree node | | | valueKey | string `('value')` | Set the `key` of the tree node value in `data` | | | virtualized | boolean | Whether to enable virtualized lists | | #### `ts:TreeNode` ```ts interface TreeNode { /** The value of the option corresponds to the `valueKey` in the data. **/ value: string | number; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** The data of the child option corresponds to the `childrenKey` in the data. */ children?: TreeNode[]; } ``` #### `ts:ListProps` ```ts interface ListProps { /** * Size of a item in the direction being windowed. */ itemSize?: number | ((index: number) => number); /** * Scroll offset for initial render. */ initialScrollOffset?: number; /** * Called when the items rendered by the list change. */ onItemsRendered?: (props: ListOnItemsRenderedProps) => void; /** * Called when the list scroll positions changes, as a result of user scrolling or scroll-to method calls. */ onScroll?: (props: ListOnScrollProps) => void; } ``` ## Related components - [``](/components/tree) - [``](/components/tree-picker) - [``](/components/check-tree-picker) [listprops]: #code-ts-list-props-code [node]: #code-ts-tree-node-code ================================================================================ # Components: Check Tree Picker - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/check-tree-picker/en-US/index.md ================================================================================ # CheckTreePicker CheckTreePicker are supported in multiple selectors for multiple selection of complex data structures. ## Import **Main import:** ```js import { CheckTreePicker } from 'rsuite'; ``` **Individual import:** ```js import CheckTreePicker from 'rsuite/CheckTreePicker'; // (Optional) Import component styles. import 'rsuite/CheckTreePicker/styles/index.css'; ``` ## Examples ### Basic ```js import { CheckTreePicker, VStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { CheckTreePicker } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { CheckTreePicker, VStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Cascade The cascade attribute can set whether or not CheckTreePicker can consider the cascade relationship of the parent parent when selecting. The default value is true. ```js import { CheckTreePicker } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { const [cascade, setCascade] = React.useState(false); return (
{ setCascade(checked); }} > Cascade
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Show Indent Lines ```js import { CheckTreePicker, VStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Placement and Prevent overflow ```js import { CheckTreePicker } from 'rsuite'; import { mockTreeData } from './mock'; import PlacementContainer from '@/components/PlacementContainer'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( {({ container, placement, preventOverflow }) => ( )} ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { CheckTreePicker, VStack, HStack, Text, Divider } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const Field = ({ label, children, ...rest }) => ( {label} ); const App = () => ( }> ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom options ```js import { CheckTreePicker, Button, HStack } from 'rsuite'; import PeoplesIcon from '@rsuite/icons/Peoples'; import AdminIcon from '@rsuite/icons/Admin'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [3, 3, 4], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => ( Select } renderTreeNode={nodeData => { return ( {nodeData.label} ); }} renderValue={(value, checkedItems) => { return ( Peoples: {checkedItems.map(item => item.label).join(' , ')} ); }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Async ```js import { CheckTreePicker, Loader, HStack } from 'rsuite'; import { mockAsyncData } from './mock'; const [getNodes, fetchNodes] = mockAsyncData(); const App = () => { const [value, setValue] = React.useState([]); const [data, setData] = React.useState([]); return ( setValue(value)} onOpen={() => { if (data.length === 0) { setTimeout(() => setData(getNodes(5)), 1000); } }} renderTree={tree => { if (data.length === 0) { return ( ); } return tree; }} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Extra footer ```js import { CheckTreePicker, Checkbox, HStack } from 'rsuite'; import { mockTreeData } from './mock'; const data = mockTreeData({ limits: [4, 6, 6], labels: (layer, value, faker) => { const methodName = ['jobArea', 'jobType', 'firstName']; return faker.person[methodName[layer]](); } }); const App = () => { const [value, setValue] = React.useState([]); const handleCheckAll = (_v, checked) => { if (checked) { setValue(data.map(item => item.value)); } else { setValue([]); } }; return ( ( Check all )} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Responsive ## Accessibility ### ARIA properties **combobox** - CheckTreePicker has role `combobox`. - Has the `aria-haspopup="tree"` attribute to indicate that the combobox has a popup tree. - Has the `aria-controls` attribute to indicate the ID of the tree element. - Has the `aria-activedescendant` attribute to indicate the ID of the focused tree node. - When `label` is set, the `aria-labelledby` attribute is added to the combobox element and the tree element and is set to the value of the `id` attribute of `label`. **tree** - CheckTree has role `tree`. - CheckTree has the `aria-multiselectable=true` attribute to indicate that the tree is multi-selectable. **treeitem** - CheckTree node has role `treeitem`. - Has the `aria-expanded` attribute to indicate whether the tree is open or not. - Has the `aria-checked` attribute to indicate whether the tree node is checked or not. - Has the `aria-level` attribute to indicate the level of the tree node. - Has the `aria-disabled` attribute to indicate whether the tree node is disabled or not. ### Keyboard interactions - - Move focus to the next tree node. - - Move focus to the previous tree node. - - Expand the focused tree node if it is collapsed. - - Collapse the focused tree node if it is expanded. - Enter - Select the focused tree node. - Esc - Close the tree. ## Props ### `` | Property | Type `(Default)` | Description | | ----------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------- | | appearance | 'default' \| 'subtle' `('default')` | The appearance of the component | | block | boolean | Whether to take up the full width of the parent container | | caretAs | ElementType | Custom component for the caret icon | | cascade | boolean | Whether to enable cascade selection | | childrenKey | string `('children')` | Set the `key` of the child node of the tree node in `data` | | cleanable | boolean `(true)` | Whether to display the clear button | | container | HTMLElement \| (() => HTMLElement) | Specify the container for the popup | | countable | boolean `(true)` | Whether to display the number of selected tree node | | data \* | [TreeNode][node][] | Data to render the tree | | defaultExpandAll | boolean | Default expand all nodes | | defaultExpandItemValues | string[] | Set the value of the default expanded node | | defaultValue | string[] | Default selected Value | | disabled | boolean | Whether the component is disabled | | disabledItemValues | string[] | Disabled tree node values | | expandItemValues | string[] | Set the value of the expanded node (controlled) | | getChildren | (item: [TreeNode][node]) => Promise<[TreeNode][node]> | Load node children data asynchronously | | labelKey | string `('label')` | Set the tree node display content to the `key` in `data` | | listProps | [ListProps][listprops] | Properties of virtualized lists | | loading | boolean `(false)` | Whether the component is in a loading state | | locale | [PickerLocaleType](/guide/i18n/#pickers) | Localization configuration | | onCascadeChange | (values:string[], event:SyntheticEvent) => void | In the cascade case, the leaf node's value change callbacks | | onChange | (values:string[]) => void | Called when the tree value changes | | onClean | (event) => void | Called when the clear button is clicked | | onClose | () => void | Called when the popup is closed | | onEnter | () => void | Called when the popup is about to open | | onEntered | () => void | Called when the popup is opened | | onEntering | () => void | Called when popup opening is in progress | | onExit | () => void | Called when the popup is about to close | | onExited | () => void | Called when the popup is closed | | onExiting | () => void | Called when popup closing is in progress | | onExpand | (expandItemValues: string[], item: [TreeNode][node], concat:(data, children) => Array) => void | Called when the tree node expands the child node | | onOpen | () => void | Called when the popup is opened | | onSearch | (search:string, event) => void | Called when the search box input changes | | onSelect | (item:[TreeNode][node], value:string, event) => void | Called when the tree node is selected | | open | boolean | Whether the popup is displayed | | placeholder | ReactNode `('Select')` | Placeholder content when there is no value | | placement | [Placement](#code-ts-placement-code) `('bottomStart')` | The placement of the popup | | popupClassName | string | Custom class name for the popup | | popupStyle | CSSProperties | Custom style for the popup | | preventOverflow | boolean | Prevent popup element overflow | | renderExtraFooter | () => ReactNode | Custom render extra footer | | renderTree | (tree:ReactNode) => ReactNode | Custom render tree | | renderTreeIcon | (item:[TreeNode][node], expanded: boolean) => ReactNode | Custom render tree node icon | | renderTreeNode | (item:[TreeNode][node]) => ReactNode | Custom render tree node | | renderValue | (values:string[], checkedItems:[TreeNode][node][],selectedElement: ReactNode) => ReactNode | Custom render selected items | | searchable | boolean `(true)` | Whether display search input box | | searchBy | (keyword: string, label: ReactNode, item: [TreeNode][node]) => boolean | Custom search method | | showIndentLine | boolean | Whether to show the indent line | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | The size of the component | | toggleAs | ElementType `('a')` | Custom component for the toggle button | | treeHeight | number `(320)` | The height of the tree | | uncheckableItemValues | string[] | Set the tree node values that do not display checkboxes | | value | string[] | Selected value | | valueKey | string `('value')` | Set the `key` of the tree node value in `data` | | virtualized | boolean | Whether to enable virtualized lists | #### `ts:TreeNode` ```ts interface TreeNode { /** The value of the option corresponds to the `valueKey` in the data. **/ value: string | number; /** The content displayed by the option corresponds to the `labelKey` in the data. **/ label: ReactNode; /** The data of the child option corresponds to the `childrenKey` in the data. */ children?: TreeNode[]; } ``` #### `ts:Placement` ```ts type Placement = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd' | 'auto' | 'autoVerticalStart' | 'autoVerticalEnd' | 'autoHorizontalStart' | 'autoHorizontalEnd'; ``` #### `ts:ListProps` ```ts interface ListProps { /** * Size of a item in the direction being windowed. */ itemSize?: number | ((index: number) => number); /** * Scroll offset for initial render. */ initialScrollOffset?: number; /** * Called when the items rendered by the list change. */ onItemsRendered?: (props: ListOnItemsRenderedProps) => void; /** * Called when the list scroll positions changes, as a result of user scrolling or scroll-to method calls. */ onScroll?: (props: ListOnScrollProps) => void; } ``` ## Related Components - [``](/components/check-tree) - [``](/components/tree) - [``](/components/tree-picker) [listprops]: #code-ts-list-props-code [node]: #code-ts-tree-node-code ================================================================================ # Components: Checkbox - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/checkbox/en-US/index.md ================================================================================ # Checkbox Check boxes are usually used in groups. Allow users to select one or more values ​​from a set. ## Import **Main import:** ```js import { Checkbox, CheckboxGroup } from 'rsuite'; ``` **Individual import:** ```js import Checkbox from 'rsuite/Checkbox'; import CheckboxGroup from 'rsuite/CheckboxGroup'; // (Optional) Import component styles. import 'rsuite/Checkbox/styles/index.css'; import 'rsuite/CheckboxGroup/styles/index.css'; ``` ## Examples ### Basic ```js import { Checkbox, HStack } from 'rsuite'; const App = () => ( Label Checked ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only Use the `disabled` prop to disable a checkbox or `readOnly` to make it read-only, preventing user interaction. ```js import { Checkbox, HStack } from 'rsuite'; const App = () => ( <> Default Checked Indeterminate
Default Checked Indeterminate
Default Checked Indeterminate ); function Label({ children }) { return ( ); } ReactDOM.render(, document.getElementById('root')); ``` ### Indeterminate The `indeterminate` property sets the Checkbox to an indeterminate state, mainly used in the select all or tree structure Checkbox. ```js import { Checkbox, CheckboxGroup, VStack } from 'rsuite'; const data = ['A', 'B']; const App = () => { const [value, setValue] = React.useState(['A']); const handleCheckAll = (value, checked) => setValue(checked ? data : []); const handleChange = value => setValue(value); return ( 0 && value.length < data.length} checked={value.length === data.length} onChange={handleCheckAll} > Parent Checkbox {data.map(item => ( Child Checkbox {item} ))} ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Colors Customize checkbox colors using the `color` property. Supports preset theme colors. ```js import { Checkbox, HStack } from 'rsuite'; const App = () => ( Red Orange Yellow Green Cyan Blue Violet ); ReactDOM.render(, document.getElementById('root')); ``` ### Checkbox Group Use `` to manage a group of checkboxes. The `value` prop controls which options are selected. ```js import { Checkbox, CheckboxGroup } from 'rsuite'; const App = () => ( Checkbox A Checkbox B Checkbox C Checkbox D ); ReactDOM.render(, document.getElementById('root')); ``` ### Inline Layout Add the `inline` prop to `` to arrange checkboxes horizontally instead of vertically. ```js import { Checkbox, CheckboxGroup } from 'rsuite'; const App = () => ( Checkbox A Checkbox B Checkbox C Checkbox D ); ReactDOM.render(, document.getElementById('root')); ``` ### Checkbox Group (Controlled) Manage checkbox group state with the `value` and `onChange` props for controlled component behavior. ```js import { Checkbox, CheckboxGroup } from 'rsuite'; const App = () => { const [value, setValue] = React.useState(['A', 'C']); return ( { setValue(value); }} > Checkbox A Checkbox B Checkbox C Checkbox D ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - The `role` property of the CheckboxGroup is `group`. - The `role` property of each Checkbox is `checkbox`. - If the Checkbox is disabled, set `aria-disabled` to `true`. - If the Checkbox is checked, set `aria-checked` to `true`, otherwise set it to `false`. - When partially checked, it has state `aria-checked` set to mixed. - A visible label referenced by the value of `aria-labelledby` set on the element with role `checkbox`. ### Keyboard interaction - When the Checkbox has focus, pressing the Space key changes the state of the Checkbox. ## Props ### `` | Property | Type `(default)` | Description | Version | | -------------- | ---------------------------------------------------------- | ----------------------------------------------------------------------- | ----------- | | as | ElementType`(div)` | Custom element type for the component | | | checked | boolean | Specifies whether the checkbox is selected | | | color | [Color](#code-ts-color-code) | The color of the checkbox when checked or indeterminate | ![][5.56.0] | | defaultChecked | boolean | Specifies the initial state: whether or not the checkbox is selected | | | disabled | boolean | Whether disabled | | | indeterminate | boolean | When being a checkbox , setting styles after the child part is selected | | | inputRef | Ref | Ref of input element | | | name | string | Used for the name of the form | | | onChange | (value: string \| number, checked: boolean, event) => void | Callback fired when checkbox is triggered and state changes | | | title | string | HTML title | | | value | string \| number | Correspond to the value of CheckboxGroup, determine whether to select | | ### `` | Property | Type `(default)` | Description | | ------------ | ------------------------------------------- | ----------------------------------------------------------- | | defaultValue | string[] \| number[] | The default value | | inline | boolean | Inline layout | | name | string | Used for the name of the form | | onChange | (value:string[] \| number[], event) => void | Callback fired when checkbox is triggered and state changes | | value | string[] \| number[] | Value of checked box (Controlled) | ### Type Definitions #### `ts:Color` ```ts type Color = 'red' | 'orange' | 'yellow' | 'green' | 'cyan' | 'blue' | 'violet'; ``` ================================================================================ # Components: Custom Provider - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/custom-provider/en-US/index.md ================================================================================ # CustomProvider Support personalized configurations such as localization, Right to Left, and themes. ## Import **Main import:** ```js import { CustomProvider } from 'rsuite'; ``` **Individual import:** ```js import CustomProvider from 'rsuite/CustomProvider'; ``` ## Usage ### Localization ```jsx import zhCN from 'rsuite/locales/zh_CN'; return ( ); ``` ### Right to Left ```jsx return ( ); ``` ### Themes ```jsx return ( ); ``` ### Global Configuration of Default Values for Components ```jsx const components = { Button: { defaultProps: { size: 'sm' } }, Input: { defaultProps: { size: 'sm' } } // more components... }; return ( ); ``` ### Content Security Policy The icon animations in `@rsuite/icons` use inline styles. If your project enables [Content Security Policy][csp], make sure to configure the [nonce][nonce] value. ```jsx return ( ); ``` ## Props ### `` | Property | Type`(Default)` | Description | Version | | ------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | ----------- | | components | [Components](#code-ts-components-code) | Custom component default configuration | ![][5.74.0] | | csp | { nonce: string } | Configure the [nonce][nonce] value of [Content Security Policy][csp] | ![][5.73.0] | | disableInlineStyles | boolean | Disable inline styles | ![][5.73.0] | | disableRipple | boolean | If true, the ripple effect is disabled. Affected components include: `Button`, `Nav.Item`, `Pagination` | | | formatDate | (date: Date, format?: string) => string | Return the formatted date string in the given format. The result may vary by locale. | | | locale | [Locale][locale] [`(en-GB)`][en_gb] | Configure Language Pack | | | parseDate | (date: string, format: string) => Date | Return the date parsed from string using the given format string. | | | rtl | boolean | Text and other elements go from left to right. | | | theme | 'light' \| 'dark' \| 'high-contrast' | Supported themes | | #### `ts:Components` ```ts import type { ButtonProps } from '../Button'; import type { InputProps } from '../Input'; interface ComponentProps { defaultProps: Partial; } export interface Components { Button: ComponentProps; Input: ComponentProps; // more components... } ``` [nonce]: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/nonce [csp]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP [en_gb]: https://github.com/rsuite/rsuite/blob/main/src/locales/en_GB.ts [locale]: https://github.com/rsuite/rsuite/blob/main/src/locales/index.ts ================================================================================ # Components: Date Input - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/date-input/en-US/index.md ================================================================================ # DateInput The DateInput component lets users select a date with the keyboard. ## Import **Main import:** ```js import { DateInput } from 'rsuite'; ``` **Individual import:** ```js import DateInput from 'rsuite/DateInput'; // (Optional) Import component styles. import 'rsuite/DateInput/styles/index.css'; ``` ## Examples ### Basic ```js import { DateInput } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Customize the date format ```js import { DateInput, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { DateInput, InputGroup, HStack, VStack, Text, Divider } from 'rsuite'; import CalendarIcon from '@rsuite/icons/Calendar'; const App = () => ( }> Disabled ReadOnly Plaintext ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled vs. uncontrolled value ```js import { DateInput, Stack, Button } from 'rsuite'; const App = () => { const [value, setValue] = React.useState(new Date()); const handleChange = (value, event) => { setValue(value); console.log('Controlled Change', value); }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - The DateInput component is the `` element. - When the DateInput component is disabled, the `disabled` property is added to the `` element. - When the DateInput component is read only, the `readonly` property is added to the `` element. ### Keyboard interactions - Use keyboard to navigate to the previous or next date segment. - Use keys to increase and decrease values. - Use Backspace key to delete selected value. - Use numeric key to update selected value. ## Props ### `` | Property | Type`(default)` | Description | | ------------ | ------------------------------- | --------------------------------------------------------- | | defaultValue | Date | The default value (uncontrolled) | | disabled | boolean | Whether disabled the component | | format | string `('yyyy-MM-dd')` | Format of the date when rendered in the input | | onChange | (date: Date, event) => void | Callback fired when value changed | | plaintext | boolean | Whether plaintext the component | | readOnly | boolean | Whether read only the component | | size | 'lg'〡'md'〡'sm'〡'xs' `('md')` | Date input can have different sizes | | value | Date | The selected value. Used when the component is controlled | ================================================================================ # Components: Date Picker - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/date-picker/en-US/index.md ================================================================================ # DatePicker DatePicker is a highly customizable component that allows users to enter and pick dates and times in different formats. ## Usage **Main import:** ```js import { DatePicker } from 'rsuite'; ``` **Individual import:** ```js import DatePicker from 'rsuite/DatePicker'; // (Optional) Import component styles. import 'rsuite/DatePicker/styles/index.css'; ``` ## Examples ### Basic ```js import { DatePicker } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Customize the date format ```js import { DatePicker, Stack } from 'rsuite'; import { FaCalendar, FaClock } from 'react-icons/fa'; import { BsCalendar2MonthFill } from 'react-icons/bs'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { DatePicker, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### One tap ```js import { DatePicker } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { DatePicker } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Block ```js import { DatePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Placeholder ```js import { DatePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### ISO week International Standard ISO 8601 defines that each calendar week begins on Monday and Sunday is the seventh day, [ISO week date](https://en.wikipedia.org/wiki/ISO_week_date). The calendar panel can be displayed in ISO standard via the `isoWeek` property setting. ```js import { DatePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Week start The calendar panel can be displayed in different week start days via the `weekStart` property setting. ```js import { DatePicker, SegmentedControl } from 'rsuite'; const options = [ { value: 0, label: 'Sun' }, { value: 1, label: 'Mon' }, { value: 2, label: 'Tue' }, { value: 3, label: 'Wed' }, { value: 4, label: 'Thu' }, { value: 5, label: 'Fri' }, { value: 6, label: 'Sat' } ]; const App = () => { const [weekStart, setWeekStart] = React.useState(0); return ( <>
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Show week numbers ```js import { DatePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { DatePicker, VStack, HStack, Text, Divider } from 'rsuite'; import { isBefore } from 'date-fns/isBefore'; const Field = ({ label, children, ...rest }) => ( {label} ); const App = () => ( }> isBefore(date, new Date())} /> { const month = date.getMonth(); return month === 0 || month === 11; }} format="yyyy-MM" /> hour < 8 || hour > 18} shouldDisableMinute={minute => minute % 15 !== 0} shouldDisableSecond={second => second % 30 !== 0} /> hour < 8 || hour > 18} hideMinutes={minute => minute % 15 !== 0} hideSeconds={second => second % 30 !== 0} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Loading state ```js import { DatePicker, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### With a label ```js import { DatePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Disable input `DatePicker` allows date and time input via keyboard by default, if you wish to disable it, you can disable input by setting `editable={false}`. ```js import { DatePicker, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Set the local language `DatePicker` supports local language custom configuration, but we recommend using the unified [i18n](/guide/i18n) configuration. ```js import { DatePicker } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Placement and Prevent overflow ```js import { DatePicker } from 'rsuite'; import PlacementContainer from '@/components/PlacementContainer'; const App = () => { return ( {({ container, placement, preventOverflow }) => ( )} ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom short options Clicking "Prev Day" in the example does not close the picker layer because the `closeOverlay=false` property is configured. This property is used to set whether to close the picker layer after clicking the shortcut item. The default value is `true`. ```js import { DatePicker, Stack } from 'rsuite'; import { addDays } from 'date-fns/addDays'; import { subDays } from 'date-fns/subDays'; const predefinedBottomRanges = [ { label: 'today', value: new Date() }, { label: 'Prev Day', closeOverlay: false, value: date => { return subDays(date, 1); } } ]; const predefinedRanges = [ { label: 'yesterday', value: addDays(new Date(), -1), placement: 'left' }, { label: 'today', value: new Date(), placement: 'left' }, { label: 'Prev Day', closeOverlay: false, value: date => { return subDays(date, 1); } } ]; const App = () => ( { console.log(shortcut); }} /> { console.log(shortcut); }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled vs. uncontrolled value ```js import { DatePicker, Stack } from 'rsuite'; const App = () => { const [value, setValue] = React.useState(new Date()); const handleChange = (value, event) => { setValue(value); console.log('Controlled Change', value); }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Selection range ```js import { DatePicker, InputGroup } from 'rsuite'; const App = () => ( to ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom Calendar Icon ```js import { DatePicker, Stack } from 'rsuite'; import { FaCalendar, FaCalendarWeek, FaCalendarDay, FaCalendarCheck, FaClock } from 'react-icons/fa'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom Calendar Cell ```js import { DatePicker } from 'rsuite'; const App = () => ( { const day = date.getDate(); const month = date.getMonth(); const weekday = date.getDay(); if (day === 1 && month === 9) { return {day}🎉; } if (month === 1 && day === 14) { return {day}❤️; } if (weekday === 0 || weekday === 6) { return {day}; } return day; }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom render value ```js import { DatePicker } from 'rsuite'; import { format } from 'date-fns/format'; const App = () => { return ( <> { return format(value, 'EEE, d MMM'); }} />
{ return format(value, 'EEE, d MMM'); }} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Native pickers If you only need to meet the simple date selection function, you can use the native pickers supported by the browser. ```js import { VStack, Input, Text } from 'rsuite'; const App = () => ( type="date" type="datetime-local" type="week" type="time" ); ReactDOM.render(, document.getElementById('root')); ``` ## Responsive ## Accessibility ### ARIA properties Has all ARIA properties of the DateInput component by default. - The `aria-invalid="true"` attribute is added to the `` element when the value is invalid. - When `label` is set, the `aria-labelledby` attribute is added to the `` element and the `dialog` element and is set to the value of the `id` attribute of `label`. - Has the `aria-haspopup="dialog"` attribute to indicate that the component has an interactive dialog. ### Keyboard interactions Has keyboard interaction for the DateInput component by default. - When the focus is on the calendar, use the keys to switch dates. - When the focus is on the calendar, use the Enter key to select a date. - When the DatePicker component has `editable={false}` set to disable input, use to move focus to the calendar. ## Props ### `` | Property | Type`(default)` | Description | Version | | --------------------- | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- | ----------- | | appearance | 'default' \| 'subtle' `('default')` | Set picker appearence | | | block | boolean | Blocking an entire row | | | calendarDefaultDate | Date | Calendar panel default presentation date and time | | | caretAs | ElementType | Custom component for the caret icon | | | cleanable | boolean `(true)` | Whether the selected value can be cleared | | | container | HTMLElement \| (() => HTMLElement) | Sets the rendering container | | | defaultOpen | boolean | Default value of open property | | | defaultValue | Date | The default value (uncontrolled) | | | disabled | boolean | Whether disabled the component | | | editable | boolean `(true)` | Rendered as an input, the date can be entered via the keyboard | | | format | string `('dd/MM/yyyy')` | Format of the date when rendered in the input | | | hideHours | (hour:number, date:Date) => boolean | Hide specific hour options | | | hideMinutes | (minute:number, date:Date) => boolean | Hide specific minute options | | | hideSeconds | (second:number, date:Date) => boolean | Hide specific second options | | | isoWeek | boolean | [ISO 8601 standard][iso-8601], each calendar week begins on Monday and Sunday on the seventh day | | | label | ReactNode | A label displayed at the beginning of toggle button | | | limitEndYear | number `(1000)` | Set the upper limit of the available year relative to the current selection date | | | limitStartYear | number | Set the lower limit of the available year relative to the current selection date | | | loading | boolean `(false)` | Whether to display a loading state indicator | | | locale | [DateTimeFormats](/guide/i18n/#date-time-formats) | Define localization settings to show component text in the user's regional language | | | monthDropdownProps | [MonthDropdownProps][month-dropdown-props] | Props for the month dropdown | | | onChange | (date: Date) => void | Callback fired when value changed | | | onChangeCalendarDate | (date: Date, event) => void | Callback function that changes the calendar date. | | | onClean | (event) => void | Callback fired when value clean | | | onClose | () => void | Callback fired when close component | | | onEnter | () => void | Callback fired before the overlay transitions in | | | onEntered | () => void | Callback fired after the overlay finishes transitioning in | | | onEntering | () => void | Callback fired as the overlay begins to transition in | | | oneTap | boolean | One click to complete the selection date | | | onExit | () => void | Callback fired right before the overlay transitions out | | | onExited | () => void | Callback fired after the overlay finishes transitioning out | | | onExiting | () => void | Callback fired as the overlay begins to transition out | | | onNextMonth | (date: Date) => void | Switch to the callback function for the next Month | | | onOk | (date: Date, event) => void | Click the OK callback function | | | onOpen | () => void | Callback fired when open component | | | onPrevMonth | (date: Date) => void | Switch to the callback function for the previous Month | | | onSelect | (date: Date) => void | Callback fired when date or time is selected | | | onShortcutClick | (shortcut: Range, event) => void | Callback fired when shortcut clicked | | | onToggleMonthDropdown | (open: boolean) => void | Callback function that switches to the month view | | | onToggleTimeDropdown | (open: boolean) => void | Callback function that switches to the time view | | | open | boolean | Whether open the component | | | placeholder | string | Placeholder | | | placement | [Placement](#code-ts-placement-code) `('bottomStart')` | The placement of component | | | preventOverflow | boolean | Prevent floating element overflow | | | ranges | [Range[]](#code-ts-range-code) | Custom shortcut options | | | renderCell | (date: Date) => ReactNode | Custom calendar cell rendering | ![][5.54.0] | | renderValue | (date: Date, format: string) => string | Custom render value | | | shouldDisableDate | (date:Date) => boolean | Disabled date | | | shouldDisableHour | (hour:number, date:Date) => boolean | Disabled hours | | | shouldDisableMinute | (minute:number, date:Date) => boolean | Disabled minutes | | | shouldDisableSecond | (second:number, date:Date) => boolean | Disabled seconds | | | showMeridiem | boolean | Display hours in 12 format | | | showWeekNumbers | boolean | Whether to show week numbers | | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | A picker can have different sizes | | | value | Date | The current value (controlled) | | | weekStart | 0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 `(0)` | The index of the first day of the week (0 - Sunday). If `isoWeek` is `true`, the value of `weekStart` is ignored | ![][5.62.0] | #### `ts:Placement` ```ts type Placement = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd' | 'auto' | 'autoVerticalStart' | 'autoVerticalEnd' | 'autoHorizontalStart' | 'autoHorizontalEnd'; ``` #### `ts:Range` ```ts interface Range { label: ReactNode; value: Date | ((date: Date) => Date); closeOverlay?: boolean; // Sets the position where the predefined range is displayed, the default is bottom. placement?: 'bottom' | 'left'; } ``` #### `ts:MonthDropdownProps` ```ts import type { FixedSizeListProps } from 'react-window'; interface MonthDropdownProps extends Partial { /** * The HTML element or React component to render as the root element of the MonthDropdown. */ as?: React.ElementType; /** * The HTML element or React component to render as each item in the MonthDropdown. */ itemAs?: React.ElementType; /** * The CSS class name to apply to each item in the MonthDropdown. */ itemClassName?: string; } ``` [month-dropdown-props]: #code-ts-month-dropdown-props-code [ISO-8601]: https://en.wikipedia.org/wiki/ISO_week_date ================================================================================ # Components: Date Range Input - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/date-range-input/en-US/index.md ================================================================================ # DateRangeInput The DateRangeInput components let the user select a date range with the keyboard. ## Import **Main import:** ```js import { DateRangeInput } from 'rsuite'; ``` **Individual import:** ```js import DateRangeInput from 'rsuite/DateRangeInput'; // (Optional) Import component styles. import 'rsuite/DateRangeInput/styles/index.css'; ``` ## Examples ### Basic ```js import { DateRangeInput } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ### Customize the date format ```js import { DateRangeInput, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { DateRangeInput, InputGroup, HStack, VStack, Text, Divider } from 'rsuite'; import CalendarIcon from '@rsuite/icons/Calendar'; const App = () => ( }> Disabled ReadOnly Plaintext ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled vs. uncontrolled value ```js import { DateRangeInput, VStack, HStack, Text, Divider, Button } from 'rsuite'; const App = () => { const [value, setValue] = React.useState([new Date('2023-10-01'), new Date('2023-10-31')]); const handleChange = (value, event) => { setValue(value); console.log('Controlled Change', value); }; return ( } > Controlled Value Uncontrolled Value ); }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - The DateRangeInput component is the `` element. - When the DateRangeInput component is disabled, the `disabled` property is added to the `` element. - When the DateRangeInput component is read only, the `readonly` property is added to the `` element. ### Keyboard interactions - Use keyboard to navigate to the previous or next date segment. - Use keys to increase and decrease values. - Use Backspace key to delete selected value. - Use numeric key to update selected value. ## Props ### `` | Property | Type`(default)` | Description | | ------------ | ------------------------------------------- | --------------------------------------------------------- | | character | string `(' ~ ')` | The character between the start and end dates | | defaultValue | [Date, Date]〡 null | The default value (uncontrolled) | | disabled | boolean | Whether disabled the component | | format | string `('dd/MM/yyyy')` | Format of the date when rendered in the input | | onChange | (date: [Date, Date]〡 null , event) => void | Callback fired when value changed | | plaintext | boolean | Whether plaintext the component | | readOnly | boolean | Whether read only the component | | size | 'lg'〡'md'〡'sm'〡'xs' `('md')` | Date input can have different sizes | | value | [Date, Date]〡 null | The selected value. Used when the component is controlled | ================================================================================ # Components: Date Range Picker - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/date-range-picker/en-US/index.md ================================================================================ # DateRangePicker DateRangePicker is used to quickly enter or pick a date and time range. ## Import **Main import:** ```js import { DateRangePicker } from 'rsuite'; ``` **Individual import:** ```js import DateRangePicker from 'rsuite/DateRangePicker'; // (Optional) Import component styles. import 'rsuite/DateRangePicker/styles/index.css'; ``` ## Examples ### Basic ```js import { DateRangePicker } from 'rsuite'; const App = () => { return ; }; ReactDOM.render(, document.getElementById('root')); ``` ### Customize the date format ```js import { DateRangePicker, Stack } from 'rsuite'; import { FaCalendar, FaClock } from 'react-icons/fa'; import { BsCalendar2MonthFill } from 'react-icons/bs'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { DateRangePicker } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Block ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Placeholder ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Select Whole Week, Whole Month ```js import { DateRangePicker } from 'rsuite'; import { subDays } from 'date-fns/subDays'; import { addDays } from 'date-fns/addDays'; const App = () => (

Select Whole Week

Select Whole Week, ISO 8601 standard , each calendar week begins on Monday and Sunday is the seventh day

Select Whole Week, week start from Wednesday

Select Whole Month

Custom Select

[subDays(date, 1), addDays(date, 1)]} />
); ReactDOM.render(, document.getElementById('root')); ``` ### One tap ```js import { DateRangePicker } from 'rsuite'; import { subDays } from 'date-fns/subDays'; const ranges = [ { label: 'today', value: [new Date(), new Date()] }, { label: 'yesterday', value: [subDays(new Date(), 1), subDays(new Date(), 1)] } ]; const App = () => (

Select Single Day

Select Single Week

Select ISO Week. Each calendar week begins on Monday.

Select Week, custom week start from Wednesday

Select Single Month

); ReactDOM.render(, document.getElementById('root')); ``` ### Show Week Numbers ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Show One Calendar ```js import { DateRangePicker } from 'rsuite'; import { addDays } from 'date-fns'; const predefinedRanges = [ { label: 'Today', value: [new Date(), new Date()], placement: 'left' }, { label: 'Yesterday', value: [addDays(new Date(), -1), addDays(new Date(), -1)], placement: 'left' }, { label: 'Last 7 Days', value: [addDays(new Date(), -7), new Date()], placement: 'left' }, { label: 'Last 30 Days', value: [addDays(new Date(), -30), new Date()], placement: 'left' } ]; const App = () => ( <>
); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and Readonly ```js import { DateRangePicker, HStack, VStack, Divider, Text } from 'rsuite'; import { isAfter } from 'date-fns/isAfter'; const { allowedMaxDays, allowedDays, allowedRange, beforeToday, afterToday, combine } = DateRangePicker; const Field = ({ label, description, children, ...rest }) => ( {label} {description} ); const App = () => ( }> isAfter(date, new Date())} /> ); ReactDOM.render(, document.getElementById('root')); ``` `shouldDisableDate` is a function type property that is called when the calendar is rendered and the date is selected, and the options that need to be disabled can be customized according to the business. The syntax is as follows: ```ts shouldDisableDate( date: Date, // Date used to determine if disabling is required. selectDate: Array, // Date selected. selectedDone: boolean, // Whether to choose to finish now. If `false`, only the start date is selected, waiting for the selection end date. target: 'CALENDAR' | 'TOOLBAR_BUTTON_OK' | 'TOOLBAR_SHORTCUT' | 'INPUT', // Call the target of the `shouldDisableDate` function ) => boolean ``` To make it easier to set the date you want to disable, `DateRangePicker` provides some methods for easy calling, examples: ```tsx import { DateRangePicker } from 'rsuite'; const { combine, allowedMaxDays, beforeToday } = DateRangePicker; ; ``` | Method | Type | Description | | -------------- | --------------------------------------------------------------- | -------------------------------------------------------------------- | | after | (date?: string \| Date) => boolean | Disable dates after the specified date | | afterToday | () => boolean | Disable dates after today | | allowedDays | (days: number) => boolean | Only allowed days are specified, other dates are disabled | | allowedMaxDays | (days: number) => boolean | Allow the maximum number of days specified, other dates are disabled | | allowedRange | (startDate: string \| Date, endDate: string \| Date) => boolean | Allow specified date range, other dates are disabled | | before | (date?: string \| Date) => boolean | Disable dates before the specified date | | beforeToday | () => boolean | Disable dates before today | | combine | (...args) => boolean | Used to combine multiple conditions | ### Disable input `DateRangePicker` allows date and time input via keyboard by default, if you wish to disable it, you can disable editing by setting `editable={false}`. ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Loading state ```js import { DateRangePicker, Stack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### With a label ```js import { DateRangePicker } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Predefined Date Ranges ```js import { DateRangePicker, Stack } from 'rsuite'; import { subDays } from 'date-fns/subDays'; import { startOfWeek } from 'date-fns/startOfWeek'; import { endOfWeek } from 'date-fns/endOfWeek'; import { addDays } from 'date-fns/addDays'; import { startOfMonth } from 'date-fns/startOfMonth'; import { endOfMonth } from 'date-fns/endOfMonth'; import { addMonths } from 'date-fns/addMonths'; const predefinedRanges = [ { label: 'Today', value: [new Date(), new Date()], placement: 'left' }, { label: 'Yesterday', value: [addDays(new Date(), -1), addDays(new Date(), -1)], placement: 'left' }, { label: 'This week', value: [startOfWeek(new Date()), endOfWeek(new Date())], placement: 'left' }, { label: 'Last 7 days', value: [subDays(new Date(), 6), new Date()], placement: 'left' }, { label: 'Last 30 days', value: [subDays(new Date(), 29), new Date()], placement: 'left' }, { label: 'This month', value: [startOfMonth(new Date()), new Date()], placement: 'left' }, { label: 'Last month', value: [startOfMonth(addMonths(new Date(), -1)), endOfMonth(addMonths(new Date(), -1))], placement: 'left' }, { label: 'This year', value: [new Date(new Date().getFullYear(), 0, 1), new Date()], placement: 'left' }, { label: 'Last year', value: [new Date(new Date().getFullYear() - 1, 0, 1), new Date(new Date().getFullYear(), 0, 0)], placement: 'left' }, { label: 'All time', value: [new Date(new Date().getFullYear() - 1, 0, 1), new Date()], placement: 'left' }, { label: 'Clear', value: null, placement: 'left' }, { label: 'Last week', closeOverlay: false, value: value => { const [start = new Date()] = value || []; return [ addDays(startOfWeek(start, { weekStartsOn: 0 }), -7), addDays(endOfWeek(start, { weekStartsOn: 0 }), -7) ]; }, appearance: 'default' }, { label: 'Next week', closeOverlay: false, value: value => { const [start = new Date()] = value || []; return [ addDays(startOfWeek(start, { weekStartsOn: 0 }), 7), addDays(endOfWeek(start, { weekStartsOn: 0 }), 7) ]; }, appearance: 'default' } ]; const predefinedBottomRanges = [ { label: 'Today', value: [new Date(), new Date()] }, { label: 'Yesterday', value: [addDays(new Date(), -1), addDays(new Date(), -1)] }, { label: 'This week', value: [startOfWeek(new Date()), endOfWeek(new Date())] }, { label: 'Last 7 days', value: [subDays(new Date(), 6), new Date()] }, { label: 'Last 30 days', value: [subDays(new Date(), 29), new Date()] }, { label: 'This month', value: [startOfMonth(new Date()), new Date()] }, { label: 'Last month', value: [startOfMonth(addMonths(new Date(), -1)), endOfMonth(addMonths(new Date(), -1))] }, { label: 'This year', value: [new Date(new Date().getFullYear(), 0, 1), new Date()] }, { label: 'Last year', value: [new Date(new Date().getFullYear() - 1, 0, 1), new Date(new Date().getFullYear(), 0, 0)] }, { label: 'All time', value: [new Date(new Date().getFullYear() - 1, 0, 1), new Date()] }, { label: 'Clear', value: null } ]; const App = () => ( { console.log(shortcut); }} /> { console.log(shortcut); }} /> { console.log(shortcut); }} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Controlled vs. uncontrolled value ```js import { DateRangePicker, Stack } from 'rsuite'; const App = () => { const [value, setValue] = React.useState([ new Date('2017-02-01 01:00:00'), new Date('2017-02-02 14:00:00') ]); return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Custom Calendar Icon ```js import { DateRangePicker, Stack } from 'rsuite'; import { FaCalendar, FaCalendarWeek, FaCalendarDay, FaCalendarCheck, FaClock } from 'react-icons/fa'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom render value ```js import { DateRangePicker } from 'rsuite'; import { format } from 'date-fns/format'; const App = () => { return ( <> { return format(start, 'EEE, d MMM') + ' - ' + format(end, 'EEE, d MMM'); }} />
{ return format(start, 'EEE, d MMM') + ' - ' + format(end, 'EEE, d MMM'); }} /> ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Hide Header ```js import { DateRangePicker, Stack } from 'rsuite'; const App = () => ; ReactDOM.render(, document.getElementById('root')); ``` ## Responsive ## Accessibility ### ARIA properties Has all ARIA properties of the DateRangeInput component by default. - The `aria-invalid="true"` attribute is added to the `` element when the value is invalid. - When `label` is set, the `aria-labelledby` attribute is added to the `` element and the `dialog` element and is set to the value of the `id` attribute of `label`. - Has the `aria-haspopup="dialog"` attribute to indicate that the component has an interactive dialog. ### Keyboard interactions Has keyboard interaction for the DateRangeInput component by default. ## Props ### `` | Property | Type`(default)` | Description | Version | | -------------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | ----------- | | appearance | 'default' \| 'subtle' `('default')` | Set picker appearence | | | block | boolean | Blocking an entire row | | | calendarSnapping | boolean | If the user selects a date on the right calendar first, it will automatically switch to the left calendar | ![][5.69.0] | | caretAs | ElementType | Custom component for the caret icon | | | character | string `(' ~ ')` | The character that separates two dates | | | cleanable | boolean `(true)` | Whether the selected value can be cleared | | | container | HTMLElement \| (() => HTMLElement) | Sets the rendering container | | | defaultCalendarValue | [Date, Date] | Default calendar panel date | | | defaultOpen | boolean | Default value of open property | | | defaultValue | [Date, Date] | The default value (uncontrolled) | | | disabled | boolean | Whether disabled the component | | | ~disabledDate~ | (date:Date) => boolean | ⚠️`[Deprecated]` Use `shouldDisableDate` instead | | | editable | boolean `(true)` | Rendered as an input, the date can be entered via the keyboard | | | format | string `('dd/MM/yyyy')` | Format of the date when rendered in the input | | | hideHours | (hour:number, date:Date) => boolean | Hide specific hour options | ![][5.71.0] | | hideMinutes | (minute:number, date:Date) => boolean | Hide specific minute options | ![][5.71.0] | | hideSeconds | (second:number, date:Date) => boolean | Hide specific second options | ![][5.71.0] | | hoverRange | unions: 'week', 'month' or (date: Date) => [Date, Date] | The date range that will be selected when you click on the date | | | isoWeek | boolean | [ISO 8601 standard][iso-8601], each calendar week begins on Monday and Sunday on the seventh day | | | label | ReactNode | A label displayed at the beginning of toggle button | | | limitEndYear | number `(1000)` | Sets the upper limit of the available year relative to the current selection date | | | limitStartYear | number | Sets the lower limit of the available year relative to the current selection date | | | loading | boolean `(false)` | Whether to display a loading state indicator | | | locale | [DateTimeFormats](/guide/i18n/#date-time-formats) | Define localization settings to show component text in the user's regional language | | | monthDropdownProps | [MonthDropdownProps][month-dropdown-props] | Props for the month dropdown | | | onChange | (value: [Date, Date]) => void | Callback fired when value changed | | | onClean | (event) => void | Callback fired when value clean | | | onClose | () => void | Callback fired when close component | | | onEnter | () => void | Callback fired before the overlay transitions in | | | onEntered | () => void | Callback fired after the overlay finishes transitioning in | | | onEntering | () => void | Callback fired as the overlay begins to transition in | | | oneTap | boolean | Whether to click once on selected date range,Can be used with hoverRange | | | onExit | () => void | Callback fired right before the overlay transitions out | | | onExited | () => void | Callback fired after the overlay finishes transitioning out | | | onExiting | () => void | Callback fired as the overlay begins to transition out | | | onOk | (value: [Date, Date]) => void | Callback fired when clicked OK button | | | onOpen | () => void | Callback fired when open component | | | onSelect | (date:Date) => void | Callback fired when date is selected | | | onShortcutClick | (shortcut: Range, event) => void | Callback fired when shortcut clicked | | | open | boolean | whether open the component | | | placeholder | string | Setting placeholders | | | placement | [Placement](#code-ts-placement-code) `('bottomStart')` | The placement of component | | | preventOverflow | boolean | Prevent floating element overflow | | | ranges | [Range[]](#code-ts-range-code) ([Ranges](#code-ts-ranges-code)) | Set predefined date ranges the user can select from. Default: `Today`,`Yesterday`,`Last 7 days` | | | renderCell | (date: Date) => ReactNode | Custom calendar cell rendering | ![][5.77.0] | | renderTitle | (date: Date, calendarKey: 'start' \| 'end') => ReactNode | Custom render for month's title | | | renderValue | (date: [Date, Date], format: string) => string | Custom render value | | | shouldDisableDate | [DisabledDateFunction](#code-ts-disabled-date-function-code) | Disabled date | | | showHeader | boolean `(true)` | Whether to display the formatted date range at the header of the calendar | ![][5.52.0] | | showMeridiem | boolean | Display hours in 12 format | | | showOneCalendar | boolen | Whether to show only one calendar | | | showWeekNumbers | boolean | Whether to show week numbers | | | size | 'lg' \| 'md' \| 'sm' \| 'xs' `('md')` | A picker can have different sizes | | | value | [Date, Date] | The current value (controlled) | | | weekStart | 0 \| 1 \| 2 \| 3 \| 4 \| 5 \| 6 `(0)` | The index of the first day of the week (0 - Sunday). If `isoWeek` is `true`, the value of `weekStart` is ignored | ![][5.62.0] | #### `ts:Placement` ```ts type Placement = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd' | 'auto' | 'autoVerticalStart' | 'autoVerticalEnd' | 'autoHorizontalStart' | 'autoHorizontalEnd'; ``` #### `ts:Range` ```ts interface Range { label: ReactNode; value: Date | ((date: Date) => Date); closeOverlay?: boolean; // Sets the position where the predefined range is displayed, the default is bottom. placement?: 'bottom' | 'left'; } ``` #### `ts:MonthDropdownProps` ```ts import type { FixedSizeListProps } from 'react-window'; interface MonthDropdownProps extends Partial { /** * The HTML element or React component to render as the root element of the MonthDropdown. */ as?: React.ElementType; /** * The HTML element or React component to render as each item in the MonthDropdown. */ itemAs?: React.ElementType; /** * The CSS class name to apply to each item in the MonthDropdown. */ itemClassName?: string; } ``` ### `ts:Value` ```ts type Value = [Date, Date]; ``` ### `ts:DisabledDateFunction` ```ts type DisabledDateFunction = ( /** * Date used to determine if disabling is required. */ date: Date, /** * Date selected. */ selectDate?: Value, /** * Whether to choose to finish now. * If `false`, only the start date is selected, waiting for the selection end date. */ selectedDone?: boolean, /** * Call the target of the `shouldDisableDate` function. */ target?: DATERANGE_DISABLED_TARGET ) => boolean; ``` ### `ts:Ranges` ```js import { startOfDay, endOfDay, addDays, subDays } from 'date-fns'; const Ranges = [ { label: 'today', value: [startOfDay(new Date()), endOfDay(new Date())] }, { label: 'yesterday', value: [startOfDay(addDays(new Date(), -1)), endOfDay(addDays(new Date(), -1))] }, { label: 'last7Days', value: [startOfDay(subDays(new Date(), 6)), endOfDay(new Date())] } ]; ``` [month-dropdown-props]: #code-ts-month-dropdown-props-code [ISO-8601]: https://en.wikipedia.org/wiki/ISO_week_date ================================================================================ # Components: Divider - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/divider/en-US/index.md ================================================================================ # Divider Divider are used to group content horizontally or vertically. ## Import **Main import:** ```js import { Divider } from 'rsuite'; ``` **Individual import:** ```js import Divider from 'rsuite/Divider'; // (Optional) Import component styles. import 'rsuite/Divider/styles/index.css'; ``` ## Examples ### Basic ```js import { Divider, Placeholder } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Divider with Label ```js import { Divider, Placeholder, Button } from 'rsuite'; const App = () => ( <> Button} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Appearance ```js import { Divider } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Sizes ```js import { Divider } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Colors ```js import { Divider } from 'rsuite'; const App = () => ( <> ); ReactDOM.render(, document.getElementById('root')); ``` ### Vertical Divider ```js import { Divider, Button, HStack } from 'rsuite'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type | Description | Version | | -------------- | ------------------------------------------------ | ------------------------------------------------- | ---------- | | appearance | 'solid' \| 'dashed' \| 'dotted' | The appearance of the divider | | | as | ElementType `(div)` | You can use a custom element for this component | | | classPrefix | string `('divider')` | The prefix of the component CSS class | | | color | Color \| CSSProperties['color'] | The color of the divider | | | label | ReactNode | The content of the label | ![][6.0.0] | | labelPlacement | 'start' \| 'center' \| 'end' | The placement of the label | ![][6.0.0] | | size | 'xs' \| 'sm' \| 'md' \| 'lg' \| number \| string | The size of the divider | | | spacing | 'xs' \| 'sm' \| 'md' \| 'lg' \| number \| string | The spacing between the divider and its content | | | vertical | boolean | Vertical dividing line. Cannot be used with label | | #### `ts:Color` ```ts type Color = 'red' | 'orange' | 'yellow' | 'green' | 'cyan' | 'blue' | 'violet'; ``` ================================================================================ # Components: Dom Helper - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/dom-helper/en-US/index.md ================================================================================ # DOMHelper In React , we do not recommend direct manipulation of the DOM, but inside the RSUITE component, you have to directly manipulate the DOM for some considerations. If you have similar requirements, you can use this method directly. ## Import **Main import:** ```js import { DOMHelper } from 'rsuite'; ``` **Individual import:** ```js import DOMHelper from 'rsuite/DOMHelper'; ``` ## APIs ### class ```typescript hasClass: (node: HTMLElement, className: string) => boolean; addClass: (node: HTMLElement, className: string) => HTMLElement; removeClass: (node: HTMLElement, className: string) => HTMLElement; toggleClass: (node: HTMLElement, className: string) => HTMLElement; ``` ```js import { ButtonToolbar, Button, DOMHelper } from 'rsuite'; const { addClass, removeClass, toggleClass, hasClass } = DOMHelper; const App = () => { const [html, setHtml] = React.useState('
'); const containerRef = React.useRef(); const viewRef = React.useRef(); const viewHtmlCode = () => { setHtml(containerRef.current.innerHTML); }; return (
{html}

); }; ReactDOM.render(, document.getElementById('root')); ``` ### style ```typescript addStyle: (node: HTMLElement, property: string, value: string) => void; addStyle: (node: HTMLElement, style: Object) => void; removeStyle: (node: HTMLElement, property: string) => void; removeStyle: (node: HTMLElement, propertys: Array) => void; getStyle: (node: HTMLElement, property: string) => string; getStyle: (node: HTMLElement) => Object; ``` ```js import { ButtonToolbar, Button, DOMHelper } from 'rsuite'; const { addStyle, removeStyle, getStyle } = DOMHelper; const App = () => { const [html, setHtml] = React.useState('
'); const containerRef = React.useRef(); const viewRef = React.useRef(); const viewHtmlCode = () => { setHtml(containerRef.current.innerHTML); }; return (
{html}

); }; ReactDOM.render(, document.getElementById('root')); ``` ### events ```typescript on: (target: HTMLElement, eventName: string, listener: Function, capture: boolean = false) => {off: Function}; off: (target: HTMLElement, eventName: string, listener: Function, capture: boolean = false) => void; ``` ```js import { ButtonToolbar, Button, DOMHelper } from 'rsuite'; const { on, off } = DOMHelper; const App = () => { const btnRef = React.useRef(); const listenerRef = React.useRef(); const handleOnEvent = () => { if (!listenerRef.current) { listenerRef.current = on(btnRef.current, 'click', () => { alert('click'); }); } }; const handleOffEvent = () => { if (listenerRef.current) { listenerRef.current.off(); listenerRef.current = null; } }; return (

); }; ReactDOM.render(, document.getElementById('root')); ``` ### scroll ```typescript scrollLeft: (node: HTMLElement) => number; scrollLeft: (node: HTMLElement, value: number) => void; scrollTop: (node: HTMLElement) => number; scrollTop: (node: HTMLElement, value: number) => void; ``` ```js import { ButtonToolbar, Button, DOMHelper } from 'rsuite'; const { scrollTop } = DOMHelper; const App = () => { return (
); }; ReactDOM.render(, document.getElementById('root')); ``` ### query ```typescript getHeight: (node: HTMLElement, client: HTMLElement) => number; getWidth: (node: HTMLElement, client: HTMLElement) => number; getOffset: (node: HTMLElement) => Object; getOffsetParent: (node: HTMLElement) => HTMLElement; getPosition: (node: HTMLElement, offsetParent: HTMLElement) => Object; contains: (context: HTMLElement, node: HTMLElement) => boolean; ``` ```js import { ButtonToolbar, Button, DOMHelper } from 'rsuite'; const { getOffset, getOffsetParent, getPosition } = DOMHelper; const App = () => { const nodeRef = React.useRef(); return (
Node
); }; ReactDOM.render(, document.getElementById('root')); ``` ### DOMMouseMoveTracker Mouse drag tracker ```typescript new DOMMouseMoveTracker( onMove:(deltaX: number, deltaY: number, moveEvent: Object) => void, onMoveEnd:() => void, container: HTMLElement ); ``` ```js import { Button, DOMHelper } from 'rsuite'; const { DOMMouseMoveTracker } = DOMHelper; const App = () => { const [left, setLeft] = React.useState(0); const [top, setTop] = React.useState(0); const mouseMoveTracker = React.useRef(); const onMove = React.useCallback((deltaX, deltaY) => { setLeft(x => x + deltaX); setTop(y => y + deltaY); }, []); const onMoveEnd = React.useCallback(() => { if (mouseMoveTracker.current) { mouseMoveTracker.current.releaseMouseMoves(); } }, []); const getMouseMoveTracker = React.useCallback(() => { return mouseMoveTracker.current || new DOMMouseMoveTracker(onMove, onMoveEnd, document.body); }, []); const handleMouseDown = React.useCallback(event => { mouseMoveTracker.current = getMouseMoveTracker(); mouseMoveTracker.current.captureMouseMoves(event); }, []); return (
{left}, {top}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Reference - https://github.com/react-bootstrap/react-bootstrap - https://github.com/facebook/fbjs ================================================================================ # Components: Drawer - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/drawer/en-US/index.md ================================================================================ # Drawer A panel that slides out from the edge of the page can replace Modal to present more content. ## Import **Main import:** ```js import { Drawer } from 'rsuite'; ``` **Individual import:** ```js import Drawer from 'rsuite/Drawer'; // (Optional) Import component styles. import 'rsuite/Drawer/styles/index.css'; ``` - `Drawer` The container of Drawer. - `Drawer.Body` The content of Drawer. - `Drawer.Actions` The action buttons of Drawer, usually placed in the header of Drawer. (optional) - `Drawer.Header` The header of Drawer, including the close button. (optional) - `Drawer.Title` The title of Drawer, usually placed in the header of Drawer. (optional) ## Examples ### Basic ```js import { Drawer, ButtonToolbar, Button, Placeholder } from 'rsuite'; const App = () => { const [open, setOpen] = React.useState(false); const [openWithHeader, setOpenWithHeader] = React.useState(false); return ( <> setOpen(false)}> setOpenWithHeader(false)}> Drawer Title ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Backdrop Control the behavior of the Drawer's backdrop: - `true`: Show backdrop, and clicking it will close the Drawer - `false`: Do not show backdrop - `'static'`: Show backdrop, but clicking it will not close the Drawer ```js import { Drawer, SegmentedControl, ButtonToolbar, Button, Placeholder, Text } from 'rsuite'; const App = () => { const [backdrop, setBackdrop] = React.useState('static'); const [open, setOpen] = React.useState(false); return ( <>
setOpen(false)}> Drawer Title ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Placement The Drawer can slide out from four directions: `top`, `right`, `bottom`, `left`. ```js import { Drawer, ButtonToolbar, Button, IconButton, Placeholder } from 'rsuite'; import { RxArrowUp, RxArrowDown, RxArrowLeft, RxArrowRight } from 'react-icons/rx'; const App = () => { const [open, setOpen] = React.useState(false); const [placement, setPlacement] = React.useState(); const handleOpen = key => { setOpen(true); setPlacement(key); }; return (
} onClick={() => handleOpen('top')} /> } onClick={() => handleOpen('left')} /> } onClick={() => handleOpen('right')} /> } onClick={() => handleOpen('bottom')} />
setOpen(false)}> Drawer Title
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Size Set the width (or height, depending on the `placement` prop) of the Drawer using the `size` prop. ```js import { Drawer, SegmentedControl, ButtonToolbar, Button, IconButton, Placeholder } from 'rsuite'; const App = () => { const [size, setSize] = React.useState(); const [open, setOpen] = React.useState(false); const [placement, setPlacement] = React.useState('right'); const handleOpen = value => { setSize(value); setOpen(true); }; return ( <>

setOpen(false)}> Drawer Title ); }; ReactDOM.render(, document.getElementById('root')); ``` ### With Form Place a form inside the Drawer, suitable for scenarios requiring user input. ```js import { Form, Button, Input, Drawer, Textarea, SelectPicker, PasswordInput, PasswordStrengthMeter } from 'rsuite'; const selectData = ['Developer', 'Designer', 'Manager', 'Analyst', 'Tester'].map(item => ({ label: item, value: item })); const requirements = [ { re: /[0-9]/ }, { re: /[a-z]/ }, { re: /[A-Z]/ }, { re: /[+,:;=?@#|'<>.^*()%!-_]/ } ]; function getStrengthLevel(password) { const passed = requirements.reduce((acc, req) => acc + req.re.test(password), 0); const hasLength = password.length >= 8; // 0: very weak, 1: weak, 2: fair, 3: strong if (passed <= 1) return 0; if (passed === 2) return 1; if (passed === 3) return 2; if (passed === requirements.length && hasLength) return 3; return 2; } const strengthLabels = ['Very weak', 'Weak', 'Fair', 'Strong']; const App = () => { const [open, setOpen] = React.useState(false); const [formValue, setFormValue] = React.useState({ fullName: '', email: '', password: '', bio: '', role: '' }); const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; const level = getStrengthLevel(formValue.password); return ( <> Create New Employee Account
Full Name Enter your full name as it appears on official documents Work Email Use your company email address Create Password Brief Bio A short description of your professional background Job Role Select the role that best describes your position
); }; ReactDOM.render(, document.getElementById('root')); ``` ## Responsive On mobile devices, the maximum width of the Drawer will fill the entire screen. ## Accessibility ### ARIA Attributes - The `role` attribute of the Drawer component is set to `dialog`. - Use the `aria-labelledby` attribute to associate with Drawer.Title. - Use the `aria-describedby` attribute to provide a description for Drawer.Body. ### Keyboard Interaction - ESC can close the Drawer. This functionality can be disabled by setting `keyboard=false`. - Tab When the Drawer is open, focus automatically moves inside the Drawer. Pressing Tab cycles through focusable elements within the Drawer. - Shift + Tab Reverse cycles through focusable elements within the Drawer. - When the Drawer closes, focus returns to the element that triggered the Drawer to open. ## Props ### `` | Property | Type `(Default)` | Description | | ----------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | as | ElementType `('div')` | You can use a custom element type for this component | | autoFocus | boolean `(true)` | When set to true, the Drawer is opened and is automatically focused on its own, accessible to screen readers | | backdrop | boolean \| 'static' | When set to true, the Drawer will display the background when it is opened. Clicking on the background will close the Drawer. If you do not want to close the Drawer, set it to 'static'. | | backdropClassName | string | Add an optional extra class name to .modal-backdrop It could end up looking like class="modal-backdrop foo-modal-backdrop in". | | classPrefix | string `('drawer')` | The prefix of the component CSS class | | closeButton | ReactNode \| boolean | Custom close button, set to false to hide close button | | container | HTMLElement \| (() => HTMLElement) | Sets the rendering container | | enforceFocus | boolean `(true)` | When set to true, Drawer will prevent the focus from leaving when opened, making it easier for the secondary screen reader to access | | keyboard | boolean | close Drawer when press `esc` | | onClose | () => void | Callback fired when Drawer hide | | onEnter | () => void | Callback fired before the Drawer transitions in | | onEntered | () => void | Callback fired after the Drawer finishes transitioning in | | onEntering | () => void | Callback fired as the Drawer begins to transition in | | onExit | () => void | Callback fired right before the Drawer transitions out | | onExited | () => void | Callback fired after the Drawer finishes transitioning out | | onExiting | () => void | Callback fired as the Drawer begins to transition out | | onOpen | () => void | Callback fired when Drawer display | | open \* | boolean | Open Drawer | | placement | [Placement](#code-ts-placement-code)`(right)` | The placement of Drawer | | size | 'xs' \| 'sm' \| 'md' \| lg' \| 'full' \| number \| string | Set Drawer size | ### `` | Property | Type `(Default)` | Description | | ----------- | ------------------------- | ---------------------------------------------------- | | as | ElementType `('div')` | You can use a custom element type for this component | | classPrefix | string `('modal-header')` | The prefix of the component CSS class | | closeButton | boolean `(true)` | When set to true, a close button will be displayed | | onClose | (event) => void | Callback function when clicking the close button | | children | ReactNode | The content of the Header | ### `` | Property | Type `(Default)` | Description | | ----------- | ------------------------ | ---------------------------------------------------- | | as | ElementType `('div')` | You can use a custom element type for this component | | classPrefix | string `('modal-title')` | The prefix of the component CSS class | | children | ReactNode | The content of the Title | ### `` | Property | Type `(Default)` | Description | | ----------- | -------------------------- | ---------------------------------------------------- | | as | ElementType `('div')` | You can use a custom element type for this component | | classPrefix | string `('modal-actions')` | The prefix of the component CSS class | | children | ReactNode | The content of the Actions | ### `` | Property | Type `(Default)` | Description | | ----------- | ----------------------- | ---------------------------------------------------- | | as | ElementType `('div')` | You can use a custom element type for this component | | classPrefix | string `('modal-body')` | The prefix of the component CSS class | | children | ReactNode | The content of the Body | #### `ts:Placement` ```ts type Placement = 'top' | 'bottom' | 'right' | 'left'; ``` ================================================================================ # Components: Dropdown - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/dropdown/en-US/index.md ================================================================================ # Dropdown Used to create an easily accessible dropdown menu, providing multiple options for users to choose from ## Import **Main import:** ```js import { Dropdown } from 'rsuite'; ``` **Individual import:** ```js import Dropdown from 'rsuite/Dropdown'; // (Optional) Import component styles. import 'rsuite/Dropdown/styles/index.css'; ``` - `Dropdown` Drop-down menu. - `Dropdown.Item` Drop-down menu options. - `Dropdown.Menu` A submenu is created in the Drop-down menu. - `Dropdown.Separator` A Separator in the Drop-down menu. ## Examples ### Basic ```js import { Dropdown } from 'rsuite'; const App = () => ( New File New File with Current Profile Download As... Export PDF Export HTML Settings About ); ReactDOM.render(, document.getElementById('root')); ``` ### Trigger Set the trigger event with the `trigger` attribute, support the event: - `click` (default) - `hover` - `contextMenu` ```js import { Dropdown } from 'rsuite'; const CustomDropdown = ({ ...props }) => ( New File New File with Current Profile Download As... Export PDF Export HTML Settings About ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### Disabled You can disable the entire component or disable individual options by configuring the `disabled` property. ```js import { Dropdown, ButtonToolbar } from 'rsuite'; const App = () => ( Item 1 Item 2 Item 3 Item 1 Item 2 Item 3 - Disabled ); ReactDOM.render(, document.getElementById('root')); ``` ### Size ```js import { Dropdown, ButtonToolbar } from 'rsuite'; const SizeDropdown = props => ( New File New File with Current Profile Download As... Export PDF Export HTML Settings About ); const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ### No caret variation ```js import { Dropdown } from 'rsuite'; const App = () => ( New File New File with Current Profile Download As... Export PDF Export HTML Settings About ); ReactDOM.render(, document.getElementById('root')); ``` ### With Shortcut ```js import { Dropdown } from 'rsuite'; const App = () => ( Copy Cut Paste Paste to replace Find... Find and replace... Find next Find previous Select all Soft undo Duplicate selection Select line Find all selections ); ReactDOM.render(, document.getElementById('root')); ``` ### With Icons ```js import { Dropdown } from 'rsuite'; import PageIcon from '@rsuite/icons/Page'; import IdInfoIcon from '@rsuite/icons/IdInfo'; import DetailIcon from '@rsuite/icons/Detail'; import FileDownloadIcon from '@rsuite/icons/FileDownload'; const App = () => ( }> } shortcut="⌘ N"> New File } shortcut="⌘ ⇧ N"> New File with Current Profile } shortcut="⌘ ⇧ S"> Download As... } shortcut="⌘ P"> Export PDF ); ReactDOM.render(, document.getElementById('root')); ``` ### With Description ```js import { Dropdown, Box } from 'rsuite'; import PageIcon from '@rsuite/icons/Page'; import IdInfoIcon from '@rsuite/icons/IdInfo'; import DetailIcon from '@rsuite/icons/Detail'; import FileDownloadIcon from '@rsuite/icons/FileDownload'; const DropdownIcon = ({ as: Component }) => ( ); const App = () => ( }> } shortcut="⌘ N" description="Create a new file" > New File } shortcut="⌘ ⇧ N" description="Create a new file with current profile" > New File with Current Profile } shortcut="⌘ ⇧ S" description="Download the selected file as a word document" > Download As... } shortcut="⌘ P" description="Export the selected file as a PDF" > Export PDF ); ReactDOM.render(, document.getElementById('root')); ``` ### Separator and Panel - Use `` to set the separator. - Use the `panel` prop to set a `Dropdown.Item` as a panel. ```js import { Dropdown, Avatar } from 'rsuite'; const renderToggle = props => ( ); const App = () => (

Signed in as

Tony
Your profile Your stars Your Gists Help Settings Sign out
); ReactDOM.render(, document.getElementById('root')); ``` ### Placement ```js import { Dropdown } from 'rsuite'; import { PlacementCornerGrid } from '@/components/PlacementGrid'; const items = [ New File, New File with Current Profile, Download As..., Export PDF, Export HTML, Settings, About ]; const App = () => ( ( {items} )} /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Submenu ```js import { Dropdown } from 'rsuite'; const minWidth = 120; const App = () => ( Item 1 Item 2-1-1 Item 2-1-2 Item 2-1-3 Item 2-2 Item 2-3 Item 3-1-1 Item 3-1-2 Item 3-1-3 Item 3-2 Item 3-3 ); ReactDOM.render(, document.getElementById('root')); ``` ### Custom Toggle ```js import { Dropdown, IconButton } from 'rsuite'; import PlusIcon from '@rsuite/icons/Plus'; import PageIcon from '@rsuite/icons/Page'; import IdInfoIcon from '@rsuite/icons/IdInfo'; import DetailIcon from '@rsuite/icons/Detail'; import FileDownloadIcon from '@rsuite/icons/FileDownload'; const renderIconButton = (props, ref) => { return ( } circle color="blue" appearance="primary" /> ); }; const renderButton = (props, ref) => { return ( ); }; const App = () => ( <> }>New File }>New File with Current Profile }>Download As... }>Export PDF
}>New File }>New File with Current Profile }>Download As... }>Export PDF ); ReactDOM.render(, document.getElementById('root')); ``` ### Used with Buttons ```js import { Dropdown, ButtonToolbar, Popover, IconButton } from 'rsuite'; import ArrowDownIcon from '@rsuite/icons/ArrowDown'; import PlusIcon from '@rsuite/icons/Plus'; const renderMenu = ({ onClose, left, top, className }, ref) => { const handleSelect = eventKey => { onClose(); console.log(eventKey); }; return ( New File New File with Current Profile Download As... Export PDF Export HTML Settings About ); }; const App = () => ( } circle /> } placement="left"> New } /> ); ReactDOM.render(, document.getElementById('root')); ``` ### Routing Library The `` component works with frameworks and client side routers like Next.js and React Router. See the [Composition Guide](https://rsuitejs.com/guide/composition/#third-party-routing-library) for setup instructions. ```js import { Dropdown } from 'rsuite'; import Link from 'next/link'; const App = () => ( Guide Components Resources ); ReactDOM.render(, document.getElementById('root')); ``` ## Props ### `` | Property | Type`(default)` | Description | | ---------------- | ------------------------------------------------------ | --------------------------------------------------------------------------------------- | | activeKey | string | The option to activate the state, corresponding to the `eventkey` in the Dropdown.item. | | classPrefix | string `('dropdown')` | The prefix of the component CSS class | | defaultOpen | boolean `(false)` | Whether Dropdown is initially open | | disabled | boolean | Whether or not component is disabled | | icon | Element<typeof Icon> | Set the icon | | menuStyle | CSSProperties | The style of the menu. | | noCaret | boolean | Do not display the arrow icon | | onClose | () => void | The callback function that the menu closes | | onOpen | () => void | Menu Pop-up callback function | | onSelect | (eventKey: string, event) => void | Selected callback function | | onToggle | (open?: boolean, event?: React.SyntheticEvent) => void | Callback function for menu state switching | | open | boolean | Controlled open state | | placement | [Placement](#code-ts-placement-code) | The placement of Menu | | renderMenuButton | (props: ButtonProps, ref: Ref) => ReactElement | Custom render menu button | | renderMenuPopup | (props: MenuProps, ref: Ref) => ReactElement | Custom render menu popup | | title | ReactNode | Menu title | | trigger | [Trigger](#code-ts-trigger-code) `('click')` | Triggering events | ### `` | Property | Type`(default)` | Description | Version | | ----------- | --------------------------------- | ---------------------------------------------------- | ----------- | | active | boolean | Active the current option | | | as | ElementType`('li')` | You can use a custom element type for this component | | | children \* | ReactNode | The content of the component | | | classPrefix | string `('dropdown-item')` | The prefix of the component CSS class | | | disabled | boolean | Disable the current option | | | divider | boolean | Whether to display the divider | | | eventKey | string | The value of the current option | | | icon | Element<typeof Icon> | Set the icon | | | onSelect | (eventKey: string, event) => void | Select the callback function for the current option | | | panel | boolean | Displays a custom panel | | | shortcut | string | The dropdown item keyboard shortcut | ![][5.58.0] | ### `` | Property | Type`(default)` | Description | | -------- | -------------------------- | ----------------------------- | | icon | Element<typeof Icon> | Set the icon | | title | string | Define the title as a submenu | ### `` | Property | Type`(default)` | Description | | -------- | -------------------- | ---------------------------------------------------- | | as | ElementType `('li')` | You can use a custom element type for this component | #### `ts:Placement` ```ts type Placement = | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd'; ``` #### `ts:Trigger` ```ts type Trigger = 'click' | 'hover' | 'contextMenu' | Array<'click' | 'hover' | 'contextMenu'>; ``` ================================================================================ # Components: Form - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/form/en-US/index.md ================================================================================ # Form A set of components and models that process form data. ## Import - **Basic**: - `Form`: Used to define forms that support data validation. - `Form.Label`: Title corresponding to the form field. - `Form.Control`: Defines the control for the form field. Defaults to the `Input` component. Can customize the component through the `accepter` property. - **Layout**: - `Form.Stack`: Used to layout a group of form controls. - `Form.Group`: Used to layout a single form control. - **Field State**: - `Form.Text`: Provides help information for form fields. - `Form.ErrorMessage`: Displays error message for form fields. - **Hooks** - `useFormControl`: A hook that provides form control functionality for custom form components, enabling seamless integration with the Form component. ## Layouts --- ### Vertical Layout ```js import { Form, ButtonToolbar, Button, Input, HStack, PasswordInput, Textarea } from 'rsuite'; const FormField = ({ name, label, text, ...props }) => ( {label} {text && {text}} ); const App = () => { return (
{/* Default vertical layout */}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Fluid The `fluid` property allows the Input 100% of the form to fill the container, valid only in vertical layouts. ```js import { Form, ButtonToolbar, Button, Input, InputGroup, NumberInput, Textarea } from 'rsuite'; const FormField = ({ name, label, text, ...props }) => ( {label} {text && {text}} ); const InputGroupField = React.forwardRef((props, ref) => ( )); const App = () => (
); ReactDOM.render(, document.getElementById('root')); ``` ### Horizontal Layout ```js import { Form, Input, ButtonToolbar, Button, HStack, VStack, Textarea } from 'rsuite'; const App = () => (
Username Required Email Required Password Textarea
); ReactDOM.render(, document.getElementById('root')); ``` ### Inline Layout ```js import EyeCloseIcon from '@rsuite/icons/EyeClose'; import VisibleIcon from '@rsuite/icons/Visible'; import { Form, Button, HStack, InputGroup, Input, PasswordInput } from 'rsuite'; const App = () => ( <>
Username Required Password
); ReactDOM.render(, document.getElementById('root')); ``` ### Layout In Modal ```js import { Form, Button, Input, Modal, SelectPicker, PasswordInput, Textarea } from 'rsuite'; const selectData = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice'].map(item => ({ label: item, value: item })); const FormField = ({ name, label, text, ...props }) => ( {label} {text && {text}} ); const App = () => { const [open, setOpen] = React.useState(false); const [formValue, setFormValue] = React.useState({ name: '', email: '', password: '', textarea: '' }); const handleClose = () => { setOpen(false); }; const handleOpen = () => { setOpen(true); }; return ( <> New User
); }; ReactDOM.render(, document.getElementById('root')); ``` ## Status --- ### Help Text `` A help description can be defined below the form component. If the `tooltip` property is set, an icon will be displayed on the form component and the help description information will be displayed as ``. ```js import { Form, HStack } from 'rsuite'; const App = () => (
This field is required This field is required
); ReactDOM.render(, document.getElementById('root')); ``` ### Error Message Error message can be set in 2 ways: - The `` component passes an `errorMessage` property setting error message, and `errorPlacement` sets the location of the error message display. - Customize a prompt message. ```js import { Form, InputGroup, Input, Toggle, SelectPicker, HStack, VStack, Box, Divider } from 'rsuite'; import AvatarIcon from '@rsuite/icons/legacy/Avatar'; const errorPlacementData = [ { label: 'Static', value: 'static' }, { label: 'Bottom Start', value: 'bottomStart' }, { label: 'Bottom End', value: 'bottomEnd' }, { label: 'Top Start', value: 'topStart' }, { label: 'Top End', value: 'topEnd' }, { label: 'Left Start', value: 'leftStart' }, { label: 'Right Start', value: 'rightStart' }, { label: 'Left End', value: 'leftEnd' }, { label: 'Right End', value: 'rightEnd' } ]; const App = () => { const [errorVisible, setErrorVisible] = React.useState(true); const [errorPlacement, setErrorPlacement] = React.useState('static'); const errorMessage = errorVisible ? 'This field is required' : null; return ( } h={368} spacing={40} align="flex-start">
Input InputGroup Custom error messages {errorMessage} {errorMessage}
); }; const InputGroupField = React.forwardRef((props, ref) => ( )); const CustomErrorMessage = ({ show, children }) => { return (
{children}
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Disabled and read only ```js import { Form, Button, ButtonToolbar, RadioGroup, Radio, Checkbox, CheckboxGroup, SegmentedControl, Slider, DatePicker, DateRangePicker, CheckPicker, SelectPicker, TagPicker, InputPicker, Cascader, MultiCascader, Rate, Panel, Toggle, HStack } from 'rsuite'; import { mockTreeData } from './mock'; const tree = mockTreeData({ limits: [2, 3, 3], labels: ['Provincial', 'County', 'Town'] }); const data = ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice'].map(item => ({ label: item, value: item })); const defaultFormValue = { input: '', checkbox: [], radio: '', slider: 0, datePicker: null, dateRangePicker: null, checkPicker: [], selectPicker: '', tagPicker: [], inputPicker: '', cascader: '', multiCascader: [], rate: 0, enable: false }; const initFormValue = { input: 'A suite of React components, sensible UI design, and a friendly development experience.', checkbox: ['Node.js', 'CSS3', 'HTML5'], radio: 'HTML5', slider: 10, datePicker: new Date(), dateRangePicker: [new Date(), new Date()], checkPicker: ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice'], selectPicker: 'Eugenia', tagPicker: ['Eugenia', 'Bryan', 'Linda', 'Nancy', 'Lloyd', 'Alice'], inputPicker: 'Eugenia', cascader: '1-1-2', multiCascader: ['1-1-2', '1-1-3'], rate: 2 }; const FormField = ({ name, label, text, ...props }) => ( {label} {text && {text}} ); const App = () => { const [formValue, setFormValue] = React.useState(initFormValue); const [status, setStatus] = React.useState('disabled'); const disabled = status === 'disabled'; const readOnly = status === 'readonly'; const plaintext = status === 'plaintext'; return (
setFormValue(formValue)} > Node.js Webpack CSS3 Javascript HTML5 Node.js Webpack CSS3 Javascript HTML5
); }; ReactDOM.render(, document.getElementById('root')); ``` ## Accessibility ### ARIA properties - You should set the `aria-label` or `aria-labelledby` property for each form so that the screen reader can read the purpose of the form correctly. - Through the `controlId` prop of ``, you can set `id` on `` and set `htmlFor` on ``. In addition, `aria-labelledby` and `aria-describeby` will be generated for ``, corresponding to the `id` of `` and ``. ```jsx Username Username is required ``` HTML: ```html
Username is required
``` ### Required JavaScript features - Click the button of `type='submit'` in the Form, and the submit event of the form will be triggered automatically. ## Props ### `
` | Property | Type `(default)` | Description | | ---------------- | ----------------------------------------------------- | ------------------------------------------------------------------------------ | | checkTrigger | 'change' \| 'blur' \| 'none' `('change')` | Specifies when to trigger form validation | | disabled | boolean `(false)` | Disables the form | | errorFromContext | boolean `(true)` | Default error messages in Form.Control are sourced from Context | | fluid | boolean | Enables the Input to occupy 100% width in vertical layouts only | | formDefaultValue | object | Initial default values for the form | | formError | object | Error messages for the form | | formValue | object | Values of the form (controlled) | | layout | 'horizontal' \| 'vertical' \| 'inline' `('vertical')` | The layout style of the form | | model | Schema | Instance of SchemaModel | | nestedField | boolean `(false)` | Allows support for nested fields | | onChange | (formValue: object, event) => void | Callback triggered on data change | | onCheck | (formError: object) => void | Callback triggered on data validation | | onError | (formError: object) => void | Callback triggered on validation errors | | onReset | (formValue: object, event: FormEvent) => void | Callback triggered on form reset | | onSubmit | (formValue: object, event: FormEvent) => void | Callback triggered on form submission, only occurs when form data is validated | | plaintext | boolean `(false)` | Renders the form in plain text | | readOnly | boolean `(false)` | Sets the form to read-only mode | ### `` ![][6.0.0] | Property | Type`(default)` | Description | | ----------- | ----------------------------------------------------- | --------------------------------------------------------------- | | classPrefix | string `('form-stack')` | CSS class prefix for the component | | fluid | boolean | Enables the Input to occupy 100% width in vertical layouts only | | layout | 'horizontal' \| 'vertical' \| 'inline' `('vertical')` | The layout style of the form | | spacing | number | Spacing between form controls | ### `` | Property | Type`(default)` | Description | | ---------------------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | accepter | ElementType `(Input)` | Component to be used as the input. | | checkAsync | boolean | Enables asynchronous validation. | | checkTrigger | 'change' \| 'blur' \| 'none' | Overrides the form's validation trigger type for this control. | | classPrefix | string `('form-control')` | CSS class prefix for the component. | | errorMessage | ReactNode | Displays error messages. | | errorPlacement | [Placement](#code-ts-placement-code)`('bottomStart')` | Specifies where to display error messages. | | name \* | string | Name attribute for the control, supports nested paths like `address.city` for form value management. | | plaintext | boolean | Renders the control in plain text. | | readOnly | boolean | Sets the control to read-only mode. | | rule | checkType | Validation rule for the field. Overrides form-level `model` validation if there's a conflict, [example](/components/form-validation/#field-level-verification-rules). | | shouldResetWithUnmount | boolean`('false')` | Removes the field value and error message when the component is unmounted. | ### `` | Property | Type`(default)` | Description | | ----------- | ----------------------- | ------------------------------------------------------------------------------- | | classPrefix | string `('form-group')` | CSS class prefix for the component | | controlId | string | Assigns an id to the `` and sets `htmlFor` on the ``. | ### `` | Property | Type`(default)` | Description | | ----------- | ------------------------------- | --------------------------------------------------------------------------------- | | classPrefix | string `('form-control-label')` | CSS class prefix for the component | | htmlFor | string | The `for` attribute of the HTML label tag, defaults to the Form.Group's controlId | ### `` | Property | Type`(default)` | Description | | ----------- | --------------------------- | --------------------------------------------------------------------------------- | | classPrefix | string `('form-help-text')` | CSS class prefix for the component | | htmlFor | string | The `for` attribute of the HTML label tag, defaults to the Form.Group's controlId | | tooltip | boolean | Shows the text through a Tooltip component | ### `` | Property | Type`(default)` | Description | | ----------- | ----------------------------------------------------- | ------------------------------------------- | | classPrefix | string `('form-error-message')` | CSS class prefix for the component | | placement | [Placement](#code-ts-placement-code)`('bottomStart')` | Specifies where to display error messages | | show | boolean | Toggles the visibility of the error message | ### Form Ref | Name | Type | Description | | ------------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------- | | check | (callback?: (formError: E) => void) => boolean | Verify form data | | checkAsync | () => Promise | Asynchronously check form data | | checkForField | (fieldName: string, callback?: (checkResult: CheckResult) => void) => boolean | Checklist single field value | | checkForFieldAsync | (fieldName: string) => Promise | Asynchronous check form single field value | | cleanErrorForField | (fieldName: string, callback?: () => void) => void | Clear single field error message | | cleanErrors | (callback: () => void) => void | Clean error message | | reset | () => void | Reset form data to initial value and clear all error messages | | resetErrors | () => void | Reset error message | | submit | () => void | Trigger form submission and verify data | ### Schema Schema depends on the [schema-typed](https://github.com/rsuite/schema-typed#schema-typed) library for defining data models. #### `ts:Placement` ```ts /** * Placement options for error messages in form controls. * The `static` option is supported from v6.0.0 onwards. */ type ErrorMessagePlacement = | 'static' | 'bottomStart' | 'bottomEnd' | 'topStart' | 'topEnd' | 'leftStart' | 'leftEnd' | 'rightStart' | 'rightEnd'; ``` ## Hooks ### `useFormControl` ![][6.0.0] The `useFormControl` hook provides form control functionality for custom form components. It must be used within a `` component. ```tsx const { value, // Current field value error, // Field error message plaintext, // Whether the field is in plaintext mode readOnly, // Whether the field is read-only disabled, // Whether the field is disabled onChange, // Handler for field value changes onBlur, // Handler for field blur events onCheck, // Handler for manually triggering field validation setValue // Directly sets the field value } = useFormControl(props); ``` | Property | Type`(default)` | Description | | ---------------------- | -------------------------- | ------------------------------------------------------------------- | | checkAsync | boolean`(false)` | Whether to perform asynchronous validation | | checkTrigger | 'change' \| 'blur' \| null | The data validation trigger type, overrides the Form's checkTrigger | | errorMessage | React.ReactNode | Custom error message to display | | name | string | The name of the form field (required) | | rule | CheckType | Validation rule (from Schema) | | shouldResetWithUnmount | boolean`(false)` | Whether to remove field value and error when component unmounts | | value | any | The current value | #### Return Values | Property | Type | Description | | --------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | | disabled | boolean | Whether the field is disabled (inherited from Form) | | error | React.ReactNode | Field error message | | onBlur | () => void | Handler for field blur events | | onChange | (value: any, event: SyntheticEvent) => void | Handler for field value changes | | onCheck | (value: any) => void | Handler for manually triggering field validation | | plaintext | boolean | Whether the field is in plaintext mode (inherited from Form) | | readOnly | boolean | Whether the field is read-only (inherited from Form) | | setValue | (value: any, shouldValidate?: boolean) => void | Directly sets the field value without triggering onChange events. If shouldValidate is true, will trigger validation based on checkTrigger | | value | any | Current field value | #### Example ```jsx import { useFormControl } from 'rsuite'; function CustomField({ name, label }) { const { value, error, onChange, onBlur } = useFormControl({ name }); return (
onChange(e.target.value, e)} onBlur={onBlur} /> {error &&
{error}
}
); } // Usage ; ``` ================================================================================ # Components: Form Formik - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/form-formik/en-US/index.md ================================================================================ # Formik integration 🧩 React Suite can be coupled smoothly with [Formik](https://formik.org/). This guide will show you how to use Formik with React Suite. ## Usage The following will use the `useFormik` hook to create a simple form with the `Input` component. ```jsx import { useFormik } from 'formik'; import { Input, Button } from 'rsuite'; const App = () => { const formik = useFormik({ initialValues: { name: '' }, onSubmit: values => { console.log(values); } }); return (
{ formik.setFieldValue('name', value); }} />
); }; ``` ## Examples ### Basic ```js import { useFormik } from 'formik'; import { Input, Button, Stack } from 'rsuite'; const App = () => { const formik = useFormik({ initialValues: { name: '', email: '' }, onSubmit: values => { alert(JSON.stringify(values, null, 2)); } }); return (
{ formik.setFieldValue('name', value); }} /> { formik.setFieldValue('email', value); }} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Validation ```js import { useFormik } from 'formik'; import { Input, Button, Form } from 'rsuite'; const Field = ({ error, ...rest }) => { return ( {error} ); }; const App = () => { const formik = useFormik({ initialValues: { name: '', email: '' }, validate: values => { const errors = {}; if (!values.name) { errors.name = 'Required'; } if (!values.email) { errors.email = 'Required'; } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'Invalid email address'; } return errors; }, onSubmit: values => { alert(JSON.stringify(values, null, 2)); } }); return (
formik.setFieldValue('name', value)} /> formik.setFieldValue('email', value)} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Validation with Yup Yup is a schema builder for runtime value parsing and validation. Formik integrates well with Yup, making it easy to use Yup schemas with Formik forms. ```js import { useFormik } from 'formik'; import { Input, Button, Form } from 'rsuite'; import * as Yup from 'yup'; const Field = ({ error, ...rest }) => { return ( {error} ); }; const validationSchema = Yup.object().shape({ name: Yup.string().required('Required'), email: Yup.string().email('Invalid email address').required('Required') }); const App = () => { const formik = useFormik({ initialValues: { name: '', email: '' }, validationSchema, onSubmit: values => { alert(JSON.stringify(values, null, 2)); } }); return (
formik.setFieldValue('name', value)} /> formik.setFieldValue('email', value)} />
); }; ReactDOM.render(, document.getElementById('root')); ``` > If you prefer to use Zod, consider using the community-provided adapter [zod-formik-adapter](https://www.npmjs.com/package/zod-formik-adapter). ### Other data entry components All data entry components in React Suite can be used with Formik. The following will demonstrate how to use Formik with the `DatePicker` and `Rate` components. ```js import { useFormik } from 'formik'; import { Input, Button, Form, DatePicker, Rate } from 'rsuite'; import * as Yup from 'yup'; const Field = ({ error, as: Component = Input, ...rest }) => { return ( {error} ); }; const validationSchema = Yup.object().shape({ date: Yup.date().required('Date is required'), rating: Yup.number() .required('Rating is required') .min(2, 'Rating must be at least 2') .max(5, 'Rating must be at most 5') }); const App = () => { const formik = useFormik({ initialValues: { date: new Date(), rating: 3 }, validationSchema, onSubmit: values => { alert(JSON.stringify(values, null, 2)); } }); return (
formik.setFieldValue('date', value)} /> formik.setFieldValue('rating', value)} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ================================================================================ # Components: Form React Hook Form - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/form-react-hook-form/en-US/index.md ================================================================================ # React Hook Form integration 🧩 React Suite's form components can be used with [React Hook Form](https://react-hook-form.com/). React Hook Form is a simple, flexible and powerful form validation library that helps you easily manage form state and validation. ## Usage ```jsx import { useForm, Controller } from 'react-hook-form'; import { Input, Button, Form } from 'rsuite'; const App = () => { const defaultValues = { name: '' }; const { control, handleSubmit } = useForm({ defaultValues }); const onSubmit = data => alert(JSON.stringify(data, null, 2)); return (
( field.onChange(value)} placeholder="Name" /> )} /> ); }; ``` ## Examples ### Basic ```js import { useForm, Controller } from 'react-hook-form'; import { Input, Button, Form } from 'rsuite'; const App = () => { const defaultValues = { name: '', email: '' }; const { control, handleSubmit } = useForm({ defaultValues }); const onSubmit = data => alert(JSON.stringify(data, null, 2)); return (
( field.onChange(value)} placeholder="Name" /> )} /> ( field.onChange(value)} placeholder="Email" /> )} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Validation ```js import { useForm, Controller } from 'react-hook-form'; import { Input, Button, Form } from 'rsuite'; const Field = ({ as: Component = Input, field, error, ...rest }) => { return ( field.onChange(value)} {...rest} /> {error} ); }; const App = () => { const defaultValues = { name: '', email: '' }; const { control, handleSubmit, formState: { errors } } = useForm({ defaultValues }); const onSubmit = data => alert(JSON.stringify(data, null, 2)); return (
( )} /> ( )} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Validation with Yup react-hook-form provides a [validation resolver](https://github.com/react-hook-form/resolvers) that can be integrated with popular validation libraries, including: Yup, Zod, AJV, Joi, Superstruct, Vest, class-validator, io-ts, typanion, Ajv, TypeBox, Valibot and nope. The following is an example using Yup validation: ```js import { useForm, Controller } from 'react-hook-form'; import { Input, Button, Form } from 'rsuite'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from 'yup'; const Field = ({ as: Component = Input, field, error, ...rest }) => { return ( field.onChange(value)} {...rest} /> {error} ); }; const validationSchema = Yup.object().shape({ name: Yup.string().required('Required'), email: Yup.string().email('Invalid email address').required('Required') }); const App = () => { const defaultValues = { name: '', email: '' }; const { control, handleSubmit, formState: { errors } } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); const onSubmit = data => alert(JSON.stringify(data, null, 2)); return (
( )} /> ( )} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Other data entry components All data entry components in React Suite can be used with React Hook Form. The following example demonstrates how to use React Hook Form with the `DatePicker` and `Rate` components. ```js import { useForm, Controller } from 'react-hook-form'; import { DatePicker, Rate, Button, Form } from 'rsuite'; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from 'yup'; const Field = ({ as: Component, field, error, ...rest }) => { return ( field.onChange(value)} {...rest} /> {error} ); }; const validationSchema = Yup.object().shape({ date: Yup.date().required('Date is required'), rating: Yup.number() .required('Rating is required') .min(2, 'Rating must be at least 2') .max(5, 'Rating must be at most 5') }); const App = () => { const defaultValues = { date: new Date(), rating: 2 }; const { control, handleSubmit, formState: { errors } } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); const onSubmit = data => alert(JSON.stringify(data, null, 2)); return (
( )} /> ( )} />
); }; ReactDOM.render(, document.getElementById('root')); ``` ================================================================================ # Components: Form Validation - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/form-validation/en-US/index.md ================================================================================ # Form validation We recommend using [`schema-typed`](https://github.com/rsuite/schema-typed) to manage and validate form data. `rsuite` integrates `schema-typed` by default, and you can define the data model of the form through the `Schema` object. It can help us define data models, validate data, and generate error messages. ## Usage

Import Form and Schema

```jsx import { Form } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; ```

Use SchemaModel to define the data model

```jsx const model = SchemaModel({ name: StringType().isRequired('This field is required.'), email: StringType().isEmail('Please enter a valid email address.') }); ```

Set model for Form

```jsx const TextField = ({ name, label, accepter, ...rest }) => ( {label} ); return (
); ```
## Examples ### Default check The form will automatically trigger the data check after the `submit` event is triggered. ```js import { Form, Button, ButtonToolbar } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; const model = SchemaModel({ name: StringType().isRequired('This field is required.'), email: StringType() .isEmail('Please enter a valid email address.') .isRequired('This field is required.') }); function TextField(props) { const { name, label, accepter, ...rest } = props; return ( {label} ); } function App() { return (
); } ReactDOM.render(, document.getElementById('root')); ``` ### Schema Model Form Check needs to be used `
`, `` and `Schema` 。 - `` To define a form, you can set `formValue` and `model` for the form, and `model` is the data model created by `SchemaModel`. - `` Define a Field that corresponds to the `key` of the `SchemaModel` object via the `name` property. For detailed reference: Custom Form Components. - `SchemaModel` Define a data model, using the reference [schema](https://github.com/rsuite/schema-typed#schema-typed). - Custom trigger check: `` instance provides `check` and `checkForField` methods, used to trigger form checksum field validation ```js import { Form, Button, ButtonToolbar, PasswordInput, Row, Col } from 'rsuite'; import { SchemaModel, StringType, NumberType } from 'rsuite/Schema'; const model = SchemaModel({ name: StringType().isRequired(), email: StringType().isEmail().isRequired(), age: NumberType().range(18, 30), password: StringType().isRequired().proxy(['confirmPassword']), confirmPassword: StringType().equalTo('password') }); const TextField = React.forwardRef((props, ref) => { const { name, label, accepter, ...rest } = props; return ( {label} ); }); const App = () => { const formRef = React.useRef(); const [formError, setFormError] = React.useState({}); const [formValue, setFormValue] = React.useState({ name: '', email: '', age: '', password: '', confirmPassword: '' }); const handleSubmit = () => { if (!formRef.current.check()) { console.error('Form Error'); return; } console.log(formValue, 'Form Value'); }; const handleCheckEmail = () => { formRef.current.checkForField('email', checkResult => { console.log(checkResult); }); }; return ( ); }; ReactDOM.render(, document.getElementById('root')); ``` ### Field level Verification rules When there are more and more Fields, huge `model` codes or files are generated. And since in the definition at the top level, it is not flexible enough(ex: If a new Field is added or a Field is deleted, Normally you also need to manipulate the `model` at the top level) At this time, the verification rules of the Field level may be a better choice. It adds it when the component is mounted, and delete it when the component is unmounted. - `` supports adding verification rule for the current Field via the `rule` attribute. ```js import { Form, Button } from 'rsuite'; import { StringType } from 'rsuite/Schema'; const nameRule = StringType().isRequired('This field is required.'); const emailRule = StringType().isEmail('Please enter a valid email address.'); function UsernameField() { return ( Username ); } function EmailField() { return ( Email ); } function App() { return (
); } ReactDOM.render(, document.getElementById('root')); ``` ### Asynchronous check Under certain conditions, we need to perform asynchronous verification on the data, such as verifying whether the username is duplicated. The following example will illustrate the processing of asynchronous verification. - Set the `checkAsync` property on `` that requires asynchronous validation. - The validation rules for asynchronous validation add an object with a return value of Promise via the `addRule` method of `schema`. - The check can be triggered manually by calling `checkAsync` and `checkForFieldAsync` of `
`. ```js import { Form, Button, ButtonToolbar, Row, Col } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; function asyncCheckUsername(name) { return new Promise(resolve => { setTimeout(() => { if (name === 'abc') { resolve(false); } else { resolve(true); } }, 500); }); } const model = SchemaModel({ name: StringType() .addRule((value, data) => { return asyncCheckUsername(value); }, 'Duplicate username') .isRequired('This field is required.') }); const App = () => { const formRef = React.useRef(); const [formError, setFormError] = React.useState({}); const [formValue, setFormValue] = React.useState({ name: '' }); const handleSubmit = () => { formRef.current.checkAsync().then(result => { console.log(result); }); }; return ( Username
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Form Control All Data Entry-related components can be used in forms such as `Checkbox`, `SelectPicker`, `Slider`, and so on. But you need to use the `Form.Control` component for data management and data association with the `Form` component. - `Form.Control` used to bind data fields in a Form, passing the `name` attribute to the `key` of the SchemaModel object. - `Form.Control` the default is an `Input` component, which can be set through the ʻaccepter` component. ```js import { Form, Button, CheckboxGroup, RadioGroup, Checkbox, Radio, CheckPicker, NumberInput, Slider, DatePicker, Message, toaster, Row, Col, Toggle } from 'rsuite'; import { SchemaModel, StringType, ArrayType } from 'rsuite/Schema'; const Field = React.forwardRef((props, ref) => { const { name, message, label, accepter, error, ...rest } = props; return ( {label} {message} ); }); const model = SchemaModel({ skills: ArrayType() .minLength(2, 'Please select at least 2 types of Skills.') .isRequired('This field is required.'), status: ArrayType() .minLength(2, 'Please select at least 2 types of Status.') .isRequired('This field is required.'), level: NumberType().min(5, 'This field must be greater than 5') }); const App = () => { const formRef = React.useRef(); const [formError, setFormError] = React.useState({}); const [formValue, setFormValue] = React.useState({ number: 10, skills: ['Node.js'], browser: 'Chrome', status: ['open'], level: 1, level2: 1, createDate: new Date(), toggle: true }); const handleSubmit = () => { if (!formRef.current.check()) { toaster.push(Error); return; } toaster.push(Success); }; return (
Node.js CSS3 Javascript HTML5 Chrome FireFox IE
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Third-Party Libraries Sometimes you need to customize form components or be compatible with third-party components. For example [react-select](https://github.com/JedWatson/react-select). ```js import { Form, Button, Message, toaster, Row, Col } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; import Select from 'react-select'; const Field = React.forwardRef((props, ref) => { const { name, message, label, accepter, error, ...rest } = props; return ( {label} {message} ); }); const model = SchemaModel({ foods: StringType().isRequired('This field is required.') }); const options = [ { value: 'chocolate', label: 'Chocolate' }, { value: 'strawberry', label: 'Strawberry' }, { value: 'vanilla', label: 'Vanilla' } ]; const CustomSelect = React.forwardRef((props, ref) => { const { value, onChange, ...rest } = props; return ( {rowError ? {rowError.name.errorMessage} : null} {rowError ? {rowError.quantity.errorMessage} : null} ); }; const ProductInputControl = ({ value = [], onChange, fieldError }) => { const errors = fieldError ? fieldError.array : []; const [products, setProducts] = React.useState(value); const handleChangeProducts = nextProducts => { setProducts(nextProducts); onChange(nextProducts); }; const handleInputChange = (rowIndex, value) => { const nextProducts = [...products]; nextProducts[rowIndex] = value; handleChangeProducts(nextProducts); }; const handleMinus = () => { handleChangeProducts(products.slice(0, -1)); }; const handleAdd = () => { handleChangeProducts(products.concat([{ name: '', quantity: null }])); }; return ( Product NameQuantity {products.map((rowValue, index) => ( ))} } /> } />
); }; const App = () => { const form = React.useRef(); const [formError, setFormError] = React.useState({}); const [formValue, setFormValue] = React.useState({ orderId: '', products: [{ name: '', quantity: null }] }); return (
Order ID
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Nested fields ```js import { Form, Button, ButtonToolbar, Row, Col } from 'rsuite'; import { SchemaModel, StringType, ObjectType, NumberType, ArrayType } from 'rsuite/Schema'; const model = SchemaModel({ name: StringType().isRequired('Name is required.'), address: ObjectType().shape({ city: StringType().isRequired('City is required.'), postCode: NumberType('Post Code must be a number').isRequired('Post Code is required.') }), skills: ArrayType().of( ObjectType().shape({ name: StringType().isRequired('Skill name is required.') }) ) }); const TextField = React.forwardRef((props, ref) => { const { name, label, accepter, ...rest } = props; return ( {label} ); }); const App = () => { const form = React.useRef(); const [formError, setFormError] = React.useState({}); const [formValue, setFormValue] = React.useState({ name: 'Tom', address: { city: '', postCode: '' }, skills: [{ name: '' }, { name: '' }] }); const handleSubmit = () => { if (!form.current.check()) { console.error('Form Error'); return; } console.log(formValue, 'Form Value'); }; return (
); }; ReactDOM.render(, document.getElementById('root')); ``` ### Proxy validation ```js import { Form, Button, ButtonToolbar, PasswordInput } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; const model = SchemaModel({ password: StringType().proxy(['confirmPassword']), confirmPassword: StringType().equalTo('password') }); function TextField(props) { const { name, label, accepter, ...rest } = props; return ( {label} ); } function App() { return (
); } ReactDOM.render(, document.getElementById('root')); ``` > Note: `proxy` isn't supported when `Form` enables `nestedField` ### Custom form fields with useFormControl ![][6.0.0] The `useFormControl` hook allows you to create custom form fields that integrate seamlessly with the Form validation system. This approach gives you complete control over your form field's UI while maintaining all validation capabilities. ```js import { Form, Button, useFormControl } from 'rsuite'; import { SchemaModel, StringType } from 'rsuite/Schema'; // Custom styles for the form field const fieldStyles = { formGroup: { marginBottom: '1rem' }, label: { display: 'block', marginBottom: '0.5rem', fontWeight: 500, color: '#575757' }, inputWrapper: { position: 'relative' }, input: { width: '100%', padding: '8px 12px', border: '1px solid #e5e5ea', borderRadius: '4px', fontSize: '14px', transition: 'border-color 0.3s ease-in-out', boxSizing: 'border-box' }, inputError: { borderColor: '#f44336' }, errorMessage: { color: '#f44336', fontSize: '12px', marginTop: '4px' } }; // Custom form field component using useFormControl const CustomField = ({ name, label }) => { const { value, error, onChange, onBlur } = useFormControl({ name }); return (
onChange(e.target.value, e)} onBlur={onBlur} /> {error &&
{error}
}
); }; function App() { const formRef = React.useRef(); const [formValue, setFormValue] = React.useState({ name: '', email: '' }); const model = SchemaModel({ name: StringType().isRequired('This field is required.'), email: StringType().isEmail('Please enter a valid email address.') }); const handleSubmit = () => { if (formRef.current.check()) { alert(JSON.stringify(formValue, null, 2)); } }; return (
); } ReactDOM.render(, document.getElementById('root')); ``` ## Integration with other libraries - [With Formik Integration](/components/form-formik/) - [With React Hook Form Integration](/components/form-react-hook-form/) ================================================================================ # Components: Frame - Main Documentation File: https://github.com/rsuite/rsuite/blob/main/docs/pages/components/frame/en-US/index.md ================================================================================ # Frame A layout component for wrapping page content. ## Import - `Container` provides a structural wrapper for layout elements. - `Header` represents the top section, typically containing navigation or branding. - `Content` holds the main content of the layout. - `Footer` appears at the bottom, often containing copyright or links. - `Sidebar` is a vertical section for navigation or additional content. ## Examples ### Horizontal Layout ### Right Sidebar ### Vertical Layout ### Center Layout ## Props ### `` | Property | Type `(Default)` | Description | | ----------- | ------------------------- | ----------------------------------------------- | | as | ElementType `('section')` | You can use a custom element for this component | | children | ReactNode | Primary content | | classPrefix | string `('container')` | The prefix of the component CSS class | | className | string | Additional classes | | style | CSSProperties | Additional style | ### `
` | Property | Type `(Default)` | Description | | ----------- | ------------------------ | ----------------------------------------------- | | as | ElementType `('header')` | You can use a custom element for this component | | children | ReactNode | Primary content | | classPrefix | string `('header')` | The prefix of the component CSS class | | className | string | Additional classes | | style | CSSProperties | Additional style | ### `` | Property | Type `(Default)` | Description | | ----------- | ---------------------- | ----------------------------------------------- | | as | ElementType `('main')` | You can use a custom element for this component | | children | ReactNode | Primary content | | classPrefix | string `('content')` | The prefix of the component CSS class | | className | string | Additional classes | | style | CSSProperties | Additional style | ### `