NativeBase

repository·master·Indexed 12 days ago

https://github.com/GeekyAnts/NativeBase

A mobile-first, accessible UI component library for React and React Native designed for consistent design systems across Android, iOS, and Web. Version 3.4.28 features utility props powered by Styled System, integrated accessibility via React ARIA, and a rich library of approximately 40 components. Note: The project is currently in maintenance mode and is evolving into gluestack-ui.

Tokens
37.6K
Snippets
139
Records
211
Agent score
96%

What's inside NativeBase

  1. Important Notice: NativeBase is Deprecated and Evolving into gluestack-ui

    master

    NativeBase is entering maintenance mode. The project is evolving into gluestack-ui, which is the next-generation component library designed for better performance, enhanced customization, and improved developer experience.

    Recommendation: If you are starting a new project, it is highly recommended to use gluestack-ui instead of NativeBase.

  2. Overview of NativeBase Features

    master

    NativeBase is a mobile-first, accessible component library for building consistent design systems across Android, iOS, and Web. Key features include:

    • Out of the Box Accessibility: Integrated with React ARIA and React Native ARIA to provide accessible hooks and components.
    • Utility Props: Powered by Styled System, allowing for rapid UI building using constraint-based utility style props.
    • Rich Component Library: Includes approximately 40 components such as Button, Checkbox, Flex, and Stack.
    • Highly Themeable: Core capability to customize app themes and component styles.
    • Cross-Platform: Powered by react-native-web to ensure UI consistency across Web, Android, and iOS.
    • Responsiveness: Supports responsive styles via object and array values.
    • Dark Mode: Optimized support for both light and dark modes.
  3. Modify the Next.js example pages and API routes

    master

    The Next.js example project uses a file-based routing system:

    • Pages: Edit pages/index.tsx to modify the main landing page. The page will auto-update in the browser upon saving.
    • API Routes: Files located in the pages/api directory are treated as API endpoints rather than React pages. For example, the endpoint http://localhost:3000/api/hello is defined in pages/api/hello.ts.
  4. Use Composite Components from NativeBase

    master

    NativeBase provides a collection of composite components designed to work together to build complex UI patterns. These components are exported from the src/components/composites entrypoint and include layout, feedback, navigation, and form-related components.

    Commonly used composite component groups include:

    • Overlays & Modals: Modal, Drawer, Popover, Tooltip, AlertDialog, Actionsheet, Backdrop.
    • Form Controls: FormControl, NumberInput, PinInput, TextField, Typeahead.
    • Feedback & Status: Alert, Avatar, Badge, Progress, CircularProgress, Skeleton, Toast.
    • Navigation & Selection: Breadcrumb, Accordion, Menu, Tabs (commented out in this entrypoint).
    • Layout & Positioning: Container, Center, Square, Circle, Wrap, SimpleGrid, AspectRatio.
  5. The Default NativeBase Theme Structure

    master

    The default NativeBase theme is a collection of design tokens organized into specific categories. When customizing or extending the theme, you can interact with these core properties: borderWidths, breakpoints, colors, radii, typography (including fontSizes, fontWeights, etc.), sizes, space, shadows, and opacity. The space property specifically maps to the spacing configuration.

    // The theme object structure follows this pattern:
    const theme = {
      borderWidths,
      breakpoints,
      colors,
      radii,
      ...typography,
      sizes,
      space: spacing,
      shadows,
      opacity,
    };
  6. Use the Modal composite component

    master

    The Modal component is a composite component used to create overlay dialogs. It follows a pattern where the main Modal component acts as a container for several sub-components that define its structure.

    To build a modal, you compose the following sub-components:

    • Modal.Header: For the title or header section.
    • Modal.Body: For the main content area.
    • Modal.Footer: For action buttons at the bottom.
    • Modal.CloseButton: A button to dismiss the modal.
    • Modal.Content: The wrapper for the internal layout of the modal content.
    import { Modal } from 'native-base';
    
    const MyComponent = () => (
      <Modal isOpen={true}>
        <Modal.Content>
          <Modal.Header>Modal Title</Modal.Header>
          <Modal.CloseButton />
          <Modal.Body>
            <Text>Modal content goes here.</Text>
          </Modal.Body>
          <Modal.Footer>
            <Button>Close</Button>
          </Modal.Footer>
        </Modal.Content>
      </Modal>
    );
  7. Import components from NativeBase

    master

    NativeBase provides a wide range of accessible UI components categorized into primitives (layout, basic elements) and composites (complex UI patterns). You can import them directly from the main entrypoint.

    Primitives

    Used for layout and basic building blocks:

    • Layout: Box, Stack, VStack, HStack, ZStack, Flex, Container, Center, Square, Circle, SimpleGrid, Wrap.
    • Basic Elements: Text, Heading, Button, Input, TextArea, Checkbox, Radio, Switch, Select, Image, Icon.
    • Feedback/Status: Spinner, Progress, Skeleton.

    Composites

    Used for complex user interactions:

    • Overlays: Modal, Drawer, Popover, AlertDialog, Actionsheet, Tooltip, Backdrop.
    • Navigation/Selection: Breadcrumb, Menu, Typeahead, Accordion.
    • Form Controls: FormControl, PinInput, NumberInput, TextField.
    • Transitions: Fade, ScaleFade, Slide, SlideFade, PresenceTransition, Stagger.
    import {
      Box,
      Text,
      Button,
      VStack,
      HStack,
      Input,
      Modal,
      useToast
    } from 'native-base';
    
    // Example usage
    const MyComponent = () => (
      <VStack space={4}>
        <Box bg="primary.500" p={4}>
          <Text color="white">Hello NativeBase</Text>
        </Box>
        <Button onPress={() => {}}>
          Click Me
        </Button>
      </VStack>
    );
  8. Configure Jest for iOS testing in NativeBase examples

    master

    When setting up Jest for iOS testing in environments using Expo, use the jest-expo/ios preset. To ensure NativeBase and its dependencies are correctly transformed by Jest, you must include them in the transformIgnorePatterns regex. This prevents Jest from ignoring these specific modules in node_modules during the transformation process.

    Key configuration requirements:

    • Preset: Use jest-expo/ios.
    • Transform Ignore Patterns: Must include native-base and related mobile dependencies (like react-native, expo, and react-navigation) to avoid transformation errors.
    • Setup Files: Use a global mock file (e.g., <rootDir>/__mocks__/globalMock.js) via setupFilesAfterEnv to handle environment-specific globals.
    const config = {
      preset: 'jest-expo/ios',
      transformIgnorePatterns: [
        '<rootDir>/../node_modules/(?!(jest-)?react-native|react-clone-referenced-element|@react-native-community|expo(nent)?|@expo(nent)?/.*|react-navigation|@react-navigation/.*|unimodules|sentry-expo|native-base|@sentry/.*)',
      ],
      setupFilesAfterEnv: ['<rootDir>/__mocks__/globalMock.js'],
    };
    
    module.exports = config;
  9. Configure NativeBase dependencies and strict mode

    master

    The nativebase.config.ts file allows you to extend NativeBase by providing external dependencies and configuring the library's strict mode.

    • dependencies: An object used to map specific component requirements to external libraries. For example, to enable gradient support in an Expo environment, you must map 'linear-gradient' to the LinearGradient component from expo-linear-gradient.
    • strictMode: (Currently commented out in example) A configuration option that can be set to 'warn' to enable stricter validation/warnings during development.
    import { INativebaseConfig } from 'native-base';
    
    export default {
      dependencies: {
        'linear-gradient': require('expo-linear-gradient').LinearGradient,
      },
      // strictMode: 'warn',
    } as INativebaseConfig;
  10. Configure Metro resolver for peerDependencies in RNBareExample

    master

    In the RNBareExample project, the metro.config.js is configured to prevent multiple versions of peerDependencies from being loaded. This is achieved by blacklisting the peerDependencies located in the project root's node_modules and aliasing them to the specific versions installed within the example's local node_modules using extraNodeModules.

    const path = require('path');
    const blacklist = require('metro-config/src/defaults/blacklist');
    const escape = require('escape-string-regexp');
    const pak = require('../package.json');
    
    const root = path.resolve(__dirname, '..');
    const modules = Object.keys({
      ...pak.peerDependencies,
    });
    
    module.exports = {
      projectRoot: __dirname,
      watchFolders: [root],
      resolver: {
        blacklistRE: blacklist(
          modules.map(
            m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`),
          ),
        ),
        extraNodeModules: modules.reduce((acc, name) => {
          acc[name] = path.join(__dirname, 'node_modules', name);
          return acc;
        }, {}),
      },
      // ...
    };