### Install React Vant Source: https://context7.com/3lang3/react-vant/llms.txt Instructions for installing the React Vant library using npm, yarn, or pnpm. This is the initial step to integrate the library into your React project. ```bash # Install via npm npm i react-vant # Or via yarn yarn add react-vant # Or via pnpm pnpm add react-vant ``` -------------------------------- ### React Vant Button Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates various configurations and states of the React Vant Button component. Includes examples for different types, sizes, shapes, loading states, plain styles, button groups, custom colors, and block elements. ```jsx import React from 'react'; import { Button } from 'react-vant'; function ButtonDemo() { const [loading, setLoading] = React.useState(false); const handleClick = async () => { setLoading(true); await new Promise(resolve => setTimeout(resolve, 2000)); setLoading(false); }; return (
{/* Button Types */} {/* Button Sizes */} {/* Button Shapes */} {/* Loading State */} {/* Plain and Hairline */} {/* Button Group */} {/* Custom Color */} {/* Block Button */}
); } ``` -------------------------------- ### React Vant Input Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt This snippet showcases various functionalities of the React Vant Input component. It includes examples for basic input, clearable inputs, different input types (tel, password, number), inputs with prefix and suffix content, character counting with limits, multi-line text areas with auto-sizing and word limits, disabled and readonly states, and controlling the input via refs. ```jsx import React, { useState, useRef } from 'react'; import { Input, Cell, Button, Toast } from 'react-vant'; function InputDemo() { const [value, setValue] = useState(''); const inputRef = useRef(null); return (
{/* Basic Input */} {/* With Clear Button */} {/* Input Types */} {/* With Prefix and Suffix */} 📱} suffix={} placeholder="Verification code" /> {/* Max Length with Counter */} Toast.info('Max length reached')} /> {/* Text Area */} {/* Auto-sizing Text Area */} {/* With Word Limit */} {/* Custom Word Limit Display */} ( 50 ? 'red' : 'inherit' }}> {currentCount} chars )} /> {/* Disabled and Readonly */} {/* Ref Methods */}
); } ``` -------------------------------- ### Basic React Vant App Setup Source: https://context7.com/3lang3/react-vant/llms.txt A simple React component demonstrating the basic usage of React Vant components, specifically the Button and Toast. It shows how to import and use components and trigger a toast message on button click. ```jsx import React from 'react'; import { Button, Toast } from 'react-vant'; function App() { return ( ); } export default App; ``` -------------------------------- ### React Vant Dialog Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates various ways to use the Dialog component in React Vant, including alert, confirm, custom content, and component-based usage. It requires 'react' and 'react-vant' libraries. ```jsx import React, { useState } from 'react'; import { Dialog, Button, Cell, Input } from 'react-vant'; function DialogDemo() { const [visible, setVisible] = useState(false); // Alert Dialog const showAlert = () => { Dialog.alert({ title: 'Alert Title', message: 'This is an alert message', }).then(() => { console.log('Alert confirmed'); }); }; // Confirm Dialog const showConfirm = async () => { try { await Dialog.confirm({ title: 'Confirm Action', message: 'Are you sure you want to proceed?', }); console.log('User confirmed'); } catch { console.log('User cancelled'); } }; // Round Button Theme const showRoundDialog = () => { Dialog.confirm({ title: 'Round Buttons', message: 'Dialog with round button style', theme: 'round-button', }); }; // Custom Content const showCustomDialog = () => { Dialog.show({ title: 'Custom Content', message: (

You can put any React content here

apple
), }); }; // Async Close with Loading const showAsyncDialog = () => { Dialog.confirm({ title: 'Async Operation', message: 'This will simulate an async action', onConfirm: async () => { // Simulate API call await new Promise(resolve => setTimeout(resolve, 2000)); console.log('Async operation completed'); }, }); }; // With Close Icon const showCloseableDialog = () => { Dialog.alert({ title: 'Closeable Dialog', message: 'Click the X to close', closeable: true, showConfirmButton: false, }); }; // Component-based Usage return (
{/* Component Usage */} setVisible(true)} /> { console.log('Confirmed'); setVisible(false); }} onCancel={() => setVisible(false)} >

This dialog uses component syntax

); } ``` -------------------------------- ### React Vant Toast Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates various functionalities of the React Vant Toast component, including basic message types, loading indicators, dynamic updates, custom positioning, custom icons, and handling multiple toasts. It utilizes React and the react-vant library. ```jsx import React from 'react'; import { Toast, Button, Cell } from 'react-vant'; function ToastDemo() { // Basic Toast Types const showTextToast = () => Toast.info('This is a text message'); const showSuccessToast = () => Toast.success('Operation successful'); const showFailToast = () => Toast.fail('Operation failed'); // Loading Toast const showLoadingToast = () => { const toast = Toast.loading({ message: 'Loading...', forbidClick: true, duration: 0, // Won't auto-close }); // Simulate async operation setTimeout(() => { Toast.clear(); Toast.success('Completed!'); }, 2000); }; // Dynamic Update const showDynamicToast = () => { let countdown = 3; const toast = Toast.info({ message: `Closing in ${countdown} seconds`, duration: 3000, }); const timer = setInterval(() => { countdown--; if (countdown > 0) { toast.config({ message: `Closing in ${countdown} seconds` }); } else { clearInterval(timer); } }, 1000); }; // Custom Position const showTopToast = () => Toast.info({ message: 'Top position', position: 'top' }); const showBottomToast = () => Toast.info({ message: 'Bottom position', position: 'bottom' }); // Custom Icon const showCustomIconToast = () => { Toast.info({ message: 'Custom icon', icon: 🎉, }); }; // Multiple Toasts (enable multiple mode first) const showMultipleToasts = () => { Toast.allowMultiple(); Toast.info('First toast'); setTimeout(() => Toast.success('Second toast'), 500); setTimeout(() => Toast.fail('Third toast'), 1000); }; // Global Configuration const setGlobalConfig = () => { Toast.setDefaultOptions({ duration: 5000 }); Toast.setDefaultOptions('loading', { forbidClick: true }); }; return (
); } ``` -------------------------------- ### React Vant Cell Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates various ways to use the React Vant Cell component, including basic usage, with icons, as clickable links, in card style, different sizes, centered content, and custom content. It utilizes React and the react-vant library. ```jsx import React from 'react'; import { Cell, Toast } from 'react-vant'; import { Arrow, LocationO, PhoneO, SettingO } from '@react-vant/icons'; function CellDemo() { return (
{/* Basic Usage */} {/* With Icon */} } /> } value="+1 234 567 890" /> } isLink /> {/* Clickable with Arrow */} Toast.info('Settings')} /> {/* Card Style (Inset) */} {/* Large Size */} {/* Centered Content */} {/* Custom Content */} } value="Online" label="Last seen: 5 min ago" /> {/* Only Value (Left Aligned) */}
); } ``` -------------------------------- ### Import and Render a Button Component in React Source: https://github.com/3lang3/react-vant/blob/main/README.md This snippet demonstrates how to import and render a basic Button component from the react-vant library within a React application. It assumes you have react-dom and react-vant installed. The code renders a default button to the DOM. ```jsx import ReactDOM from 'react-dom'; import { Button } from 'react-vant'; function App() { return ; } ReactDOM.render(, mountNode); ``` -------------------------------- ### Use Window Size Hook in React Source: https://context7.com/3lang3/react-vant/llms.txt The `useWindowSize` hook from React Vant allows you to easily get the current width and height of the browser window. It updates automatically when the window is resized. No external dependencies are required. ```jsx import React from 'react'; import { hooks } from 'react-vant'; function WindowSizeDemo() { const { width, height } = hooks.useWindowSize(); return
Window: {width}x{height}
; } ``` -------------------------------- ### React Vant Image Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt This snippet showcases the react-vant Image component, highlighting its features such as different fill modes, rounded corners, lazy loading, custom loading/error states, and event handling. It demonstrates how to enhance native image display with additional functionalities. ```jsx import React from 'react'; import { Image, Space } from 'react-vant'; function ImageDemo() { const src = 'https://img.yzcdn.cn/vant/cat.jpeg'; const errorSrc = 'https://invalid-url.jpg'; return (
{/* Basic Image */} {/* Fill Modes */} {/* Round Image */} {/* With Radius */} {/* Lazy Load */} {/* Loading State */} Loading...} /> {/* Error State */} Failed} /> {/* Event Handlers */} console.log('Image clicked')} onLoad={() => console.log('Image loaded')} onError={() => console.log('Image failed to load')} />
); } ``` -------------------------------- ### Tabs Component Examples in React Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates various functionalities of the Tabs component, including basic usage, different tab types (card, capsule), badges, scrollable tabs, disabled tabs, sticky positioning, swipe gestures, scrollspy navigation, and custom colors. It requires React and react-vant. ```jsx import React, { useState, useRef } from 'react'; import { Tabs, Toast } from 'react-vant'; function TabsDemo() { const [active, setActive] = useState(0); const tabsRef = useRef(null); return (
{/* Basic Tabs */} Content 1 Content 2 Content 3 {/* Tab Types */} Card Content 1 Card Content 2 Capsule Content 1 Capsule Content 2 {/* With Badge */} Messages content Notifications content Settings content {/* Scrollable Tabs (more than 5) */} {[1, 2, 3, 4, 5, 6, 7, 8].map(item => ( Content {item} ))} {/* Disabled Tab */} Active content Disabled content Active 2 content {/* Sticky Tabs */} {[1, 2, 3, 4].map(item => (
Scrollable content {item}
))}
{/* Scrollspy Navigation */} {[1, 2, 3, 4].map(item => (
Section {item} content
))}
{/* Custom Tab Color */} Content 1 Content 2
); } ``` -------------------------------- ### React Vant Checkbox Component Examples Source: https://context7.com/3lang3/react-vant/llms.txt This snippet demonstrates various functionalities of the react-vant Checkbox component, including basic toggling, group selection, custom styling, and toggle-all features. It utilizes React hooks like useState and useRef for managing component state and references. ```jsx import React, { useState, useRef } from 'react'; import { Checkbox, Cell, Button } from 'react-vant'; function CheckboxDemo() { const [checked, setChecked] = useState(false); const [groupValue, setGroupValue] = useState(['a']); const groupRef = useRef(null); return (
{/* Basic Checkbox */} Basic Checkbox {/* Default Checked */} Default Checked {/* Disabled State */} Disabled Disabled Checked {/* Custom Shape */} Square Shape {/* Custom Color */} Custom Color {/* Custom Size */} Large Icon {/* Label Position */} Label on Left {/* Disable Label Click */} Only icon is clickable {/* Checkbox Group */} Option A Option B Option C

Selected: {groupValue.join(', ')}

{/* Horizontal Group */} X Y Z {/* Max Selection */} Option 1 Option 2 Option 3 {/* Toggle All */} Item 1 Item 2 Item 3 {/* With Cell */} {['a', 'b', 'c'].map(name => ( ))}
); } ``` -------------------------------- ### Use Countdown Hook in React Source: https://context7.com/3lang3/react-vant/llms.txt The `useCountDown` hook provides functionality for creating countdown timers. It allows starting, pausing, and resetting the timer, and can execute a callback function upon completion. It takes an options object with `time` and `onFinish` properties. ```jsx import React from 'react'; import { hooks, Button } from 'react-vant'; function CountDownDemo() { const { current, start, pause, reset } = hooks.useCountDown({ time: 60 * 1000, // 60 seconds onFinish: () => console.log('Countdown finished'), }); return (

Time left: {current.seconds}s

); } ``` -------------------------------- ### Use Mount Hook in React Source: https://context7.com/3lang3/react-vant/llms.txt The `useMount` hook allows you to run a callback function exactly once when the component mounts. It's a convenient alternative to `useEffect` with an empty dependency array for mount-only logic. ```jsx import React from 'react'; import { hooks } from 'react-vant'; function MountDemo() { hooks.useMount(() => { console.log('Component mounted'); }); return
Check console for mount message
; } ``` -------------------------------- ### Basic Swiper with Autoplay in React Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates a basic implementation of the Swiper component with an autoplay feature. It cycles through a list of images automatically. Requires React and react-vant libraries. ```jsx import React from 'react'; import { Swiper, Image } from 'react-vant'; function SwiperDemo() { const images = [ 'https://img.yzcdn.cn/vant/apple-1.jpg', 'https://img.yzcdn.cn/vant/apple-2.jpg', 'https://img.yzcdn.cn/vant/apple-3.jpg', 'https://img.yzcdn.cn/vant/apple-4.jpg', ]; return ( {images.map((image, index) => ( ))} ); } ``` -------------------------------- ### React Vant ActionSheet Component Implementation Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates the implementation of the ActionSheet component in React Vant. It showcases how to manage the visibility of the ActionSheet, define different types of actions (basic, with subnames, with states), and handle user selections or cancellations. This snippet requires React and react-vant libraries. ```jsx import React, { useState } from 'react'; import { ActionSheet, Cell, Toast } from 'react-vant'; function ActionSheetDemo() { const [visible, setVisible] = useState(false); const [customVisible, setCustomVisible] = useState(false); // Basic Actions const basicActions = [ { name: 'Option 1' }, { name: 'Option 2' }, { name: 'Option 3' }, ]; // Actions with Subnames const detailedActions = [ { name: 'Option 1', subname: 'Description for option 1' }, { name: 'Option 2', subname: 'Description for option 2' }, { name: 'Option 3', subname: 'Description for option 3' }, ]; // Actions with States const stateActions = [ { name: 'Normal Option' }, { name: 'Colored Option', color: '#ee0a24' }, { name: 'Disabled Option', disabled: true }, { name: 'Loading Option', loading: true }, ]; return (
{/* Basic ActionSheet */} setVisible(true)} /> { Toast.info(`Selected: ${action.name}`); setVisible(false); }} onCancel={() => setVisible(false)} cancelText="Cancel" /> {/* With Description */} {/* With Different States */} {/* Custom Content */} setCustomVisible(true)} /> setCustomVisible(false)} >

You can put any custom content here

This is useful for forms or complex selections

{/* With Callback per Action */} Toast.info('Delete clicked') }, { name: 'Save', callback: () => Toast.info('Save clicked') }, { name: 'Share', callback: () => Toast.info('Share clicked') }, ]} closeOnClickAction cancelText="Cancel" />
); } ``` -------------------------------- ### Implement React Vant Popup Component Source: https://context7.com/3lang3/react-vant/llms.txt This snippet demonstrates how to use the Popup component from 'react-vant' to create various modal layers. It requires 'react' and 'react-vant' components like Popup, Button, and Cell. The component manages the visibility state for different popup positions and provides options for customization such as position, title, description, and closeability. ```jsx import React, { useState } from 'react'; import { Popup, Button, Cell } from 'react-vant'; function PopupDemo() { const [centerPopup, setCenterPopup] = useState(false); const [bottomPopup, setBottomPopup] = useState(false); const [topPopup, setTopPopup] = useState(false); const [leftPopup, setLeftPopup] = useState(false); const [rightPopup, setRightPopup] = useState(false); return (
{/* Center Popup */} setCenterPopup(true)} /> setCenterPopup(false)} style={{ padding: '30px 50px' }} > Center Content {/* Bottom Popup */} setBottomPopup(true)} /> setBottomPopup(false)} style={{ height: '40%' }} >

Bottom popup content

{/* Top Popup */} setTopPopup(true)} /> setTopPopup(false)} style={{ height: '30%' }} >
Top popup content
{/* Left Popup */} setLeftPopup(true)} /> setLeftPopup(false)} style={{ width: '60%', height: '100%' }} >
Left sidebar content
{/* Right Popup with Close Icon */} setRightPopup(true)} /> setRightPopup(false)} style={{ width: '60%', height: '100%' }} >
Right panel content
); } ``` -------------------------------- ### React Vant Dynamic Form with Form.List Source: https://context7.com/3lang3/react-vant/llms.txt Illustrates how to create a dynamic form using Form.List in React Vant. This allows for adding and removing form fields programmatically, suitable for scenarios like managing a list of contacts. It utilizes the Form and Input components from react-vant. ```jsx // Dynamic Form with Form.List function DynamicFormDemo() { return (
console.log(values)}> {(fields, { add, remove }) => ( <> {fields.map((field, index) => (
))} )}
); } ``` -------------------------------- ### React Vant Picker Component Implementation Source: https://context7.com/3lang3/react-vant/llms.txt This snippet demonstrates the core functionality of the React Vant Picker component. It showcases how to implement single-column, multi-column, and cascading selections, along with handling user interactions like confirmation and cancellation. It utilizes React hooks for state management and refs for controlling component behavior. ```jsx import React, { useState, useRef } from 'react'; import { Picker, Cell, Toast } from 'react-vant'; function PickerDemo() { const pickerRef = useRef(null); const [city, setCity] = useState(''); // Single Column const singleColumns = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']; // Multiple Columns const multiColumns = [ ['Morning', 'Afternoon', 'Evening'], ['8:00', '9:00', '10:00', '11:00', '12:00'], ]; // Cascading Data const cascadeColumns = [ { text: 'California', value: 'CA', children: [ { text: 'Los Angeles', value: 'LA' }, { text: 'San Francisco', value: 'SF' }, { text: 'San Diego', value: 'SD' }, ], }, { text: 'New York', value: 'NY', children: [ { text: 'New York City', value: 'NYC' }, { text: 'Buffalo', value: 'BUF' }, { text: 'Albany', value: 'ALB' }, ], }, ]; return (
{/* Basic Single Column */} Toast.info(`Selected: ${value}`)} onCancel={() => Toast.info('Cancelled')} /> {/* Multiple Columns */} console.log('Changed:', values)} onConfirm={(values) => Toast.info(`Selected: ${values.join(' ')}`)} /> {/* Cascading Selection */} { const location = items.map(item => item.text).join(', '); Toast.info(`Selected: ${location}`); }} /> {/* With Popup Mode */} pickerRef.current?.open()} /> setCity(value)} /> {/* Disabled Options */} {/* Loading State */} {/* Custom Field Names */}
); } ``` -------------------------------- ### Configure Global Settings with React-Vant ConfigProvider Component Source: https://context7.com/3lang3/react-vant/llms.txt The ConfigProvider component from react-vant allows for global configuration of application-wide settings such as theming and internationalization. It accepts theme variables (CSS variables) and locale objects. It can also wrap components with a custom HTML tag. Dependencies include React and specific locale files from 'react-vant/es/locale/lang'. ```jsx import React from 'react'; import { ConfigProvider, Button, Cell, Rate } from 'react-vant'; import enUS from 'react-vant/es/locale/lang/en-US'; function ConfigProviderDemo() { // Custom Theme Variables const customTheme = { '--rv-primary-color': '#7232dd', '--rv-button-primary-background-color': '#7232dd', '--rv-button-primary-border-color': '#7232dd', '--rv-rate-icon-full-color': '#7232dd', }; // Dark Theme const darkTheme = { '--rv-text-color': '#f5f5f5', '--rv-background-color': '#1a1a1a', '--rv-cell-background-color': '#2d2d2d', }; return (
{/* Custom Theme */} {/* English Locale */} {/* Combined Configuration */}
{/* Custom Tag */}
); } // Global CSS Variable Override (in your CSS file) /* :root { --rv-primary-color: #1989fa; --rv-success-color: #07c160; --rv-danger-color: #ee0a24; --rv-warning-color: #ff976a; } */ ``` -------------------------------- ### Manual Swiper Control in React Source: https://context7.com/3lang3/react-vant/llms.txt Shows how to manually control the Swiper component using previous, next, and specific slide navigation. This involves using a ref to access Swiper methods. Requires React and react-vant. ```jsx import React, { useRef } from 'react'; import { Swiper, Image, Button } from 'react-vant'; function SwiperDemo() { const swiperRef = useRef(null); const images = [ 'https://img.yzcdn.cn/vant/apple-1.jpg', 'https://img.yzcdn.cn/vant/apple-2.jpg', 'https://img.yzcdn.cn/vant/apple-3.jpg', 'https://img.yzcdn.cn/vant/apple-4.jpg', ]; return (
{images.map((image, index) => ( ))}
); } ``` -------------------------------- ### Swiper with Custom Slide Size in React Source: https://context7.com/3lang3/react-vant/llms.txt Demonstrates configuring the Swiper component with custom slide size and track offset. This affects how much of each slide is visible and the spacing. Requires React and react-vant. ```jsx import React from 'react'; import { Swiper, Image } from 'react-vant'; function SwiperDemo() { const images = [ 'https://img.yzcdn.cn/vant/apple-1.jpg', 'https://img.yzcdn.cn/vant/apple-2.jpg', 'https://img.yzcdn.cn/vant/apple-3.jpg', 'https://img.yzcdn.cn/vant/apple-4.jpg', ]; return ( {images.map((image, index) => ( ))} ); } ``` -------------------------------- ### Use Update Effect Hook in React Source: https://context7.com/3lang3/react-vant/llms.txt The `useUpdateEffect` hook is similar to `useEffect` but skips the initial render. It only runs the effect when one of its dependencies changes, making it ideal for logic that should not execute on component mount. ```jsx import React, { useState } from 'react'; import { hooks, Button } from 'react-vant'; function UpdateEffectDemo() { const [count, setCount] = useState(0); hooks.useUpdateEffect(() => { console.log('Count updated:', count); }, [count]); return ; } ```