react-native-graph

repository·main·Indexed 25 days ago

https://github.com/margelo/react-native-graph

A high-performance line graph implementation for React Native powered by the Skia graphics engine. It supports 120 FPS animations, fluid gesture interactions for scrubbing/panning, and gradient fills, making it suitable for financial and crypto applications. Key components include LineGraph and AnimatedLineGraph, with support for custom axis labels and selection indicators.

Tokens
4K
Snippets
10
Records
27
Agent score
82%

What's inside react-native-graph

  1. Configure the `animated` prop

    main

    The animated prop determines whether the graph animates between data changes.

    • When true: Uses the Skia animation system for native interpolation (up to 120 FPS). This is required for features like enablePanGesture, TopAxisLabel, BottomAxisLabel, and SelectionDot.
    • When false: Uses a lightweight renderer, which is optimal for displaying many graphs in large lists.
    <LineGraph
      points={priceHistory}
      animated={true}
      color="#4484B2"
    />
  2. Use the LineGraphProps union type

    main

    The LineGraphProps type is a discriminated union that enforces different property sets based on the animated boolean.

    • If animated: true, you must provide AnimatedLineGraphProps (which includes gesture and interaction props).
    • If animated: false, you provide StaticLineGraphProps (which only includes base styling props).
    export type LineGraphProps =
      | ({ animated: true } & AnimatedLineGraphProps)
      | ({ animated: false } & StaticLineGraphProps);
  3. Define a graph canvas range

    main

    The range prop defines the coordinate space for the graph canvas. The range must be larger than the span of the provided data points. This is useful for showing a fixed timeframe or fixed value bounds regardless of the current data.

    <LineGraph
      points={priceHistory}
      animated={true}
      color="#4484B2"
      enablePanGesture={true}
      range={{
        x: {
          min: new Date(new Date(2000, 1, 1).getTime()),
          max: new Date(
            new Date(2000, 1, 1).getTime() +
            31 * 1000 * 60 * 60 * 24
          )
        },
        y: {
          min: 0,
          max: 200
        }
      }}
    />
  4. Basic usage of LineGraph

    main

    The core component is LineGraph. You provide it with a points array and a color prop to render a line chart.

    function App() {
      const priceHistory = usePriceHistory('ethereum')
    
      return <LineGraph points={priceHistory} color="#4484B2" />
    }
  5. Enable and configure pan gestures

    main

    To allow users to scrub through the graph, set enablePanGesture={true}. This requires animated={true}.

    Gesture Events

    • onGestureStart: Fired when the user presses and holds the graph (gesture activates).
    • onPointSelected: Fired for each point the user pans through. Use this to update labels or highlights.
    • onGestureEnd: Fired when the user releases their finger (gesture deactivates).

    Configuration

    • panGestureDelay: The delay (in ms) before the pan gesture activates. Defaults to 300. Set to 0 for immediate activation.
    <LineGraph
      points={priceHistory}
      animated={true}
      color="#4484B2"
      enablePanGesture={true}
      onGestureStart={() => hapticFeedback('impactLight')}
      onPointSelected={(p) => updatePriceTitle(p)}
      onGestureEnd={() => resetPriceTitle()}
    />
  6. Render TopAxisLabel and BottomAxisLabel

    main

    You can render custom labels above or below the graph using TopAxisLabel and BottomAxisLabel. This requires animated={true}. These are typically used to display maximum and minimum values from your data points.

    <LineGraph
      points={priceHistory}
      animated={true}
      color="#4484B2"
      TopAxisLabel={() => <AxisLabel x={max.x} value={max.value} />}
      BottomAxisLabel={() => <AxisLabel x={min.x} value={min.value} />}
    />
  7. Customize the SelectionDot

    main

    The SelectionDot is the visual indicator shown during a pan gesture. This requires both animated={true} and enablePanGesture={true}. If you do not provide a component, a default one with an outer ring and light shadow is used.

    <LineGraph
      points={priceHistory}
      animated={true}
      color="#4484B2"
      enablePanGesture={true}
      SelectionDot={CustomSelectionDot}
    />
  8. Configure Metro for the react-native-graph monorepo

    main

    When working within the react-native-graph monorepo structure, the Metro configuration uses react-native-monorepo-config to correctly resolve dependencies from the root. This ensures that the bundler can access packages located in the monorepo workspace.

    To implement this configuration, use withMetroConfig wrapping the default Expo configuration, providing the root directory (the monorepo root) and the current dirname.

    const path = require('path');
    const { getDefaultConfig } = require('@expo/metro-config');
    const { withMetroConfig } = require('react-native-monorepo-config');
    
    const root = path.resolve(__dirname, '..');
    
    /**
     * Metro configuration
     * https://facebook.github.io/metro/docs/configuration
     *
     * @type {import('metro-config').MetroConfig}
     */
    const config = withMetroConfig(getDefaultConfig(__dirname), {
      root,
      dirname: __dirname,
    });
    
    module.exports = config;
  9. Add axis labels to AnimatedLineGraph

    main

    You can render custom labels at the top and bottom of the graph by passing React components to the TopAxisLabel and BottomAxisLabel props.

    These components are rendered in a container with specific padding to accommodate the labels.

    const TopLabel = () => <Text>Max Value</Text>;
    const BottomLabel = () => <Text>Min Value</Text>;
    
    <AnimatedLineGraph
      points={myData}
      TopAxisLabel={TopLabel}
      BottomAxisLabel={BottomLabel}
    />
  10. Configure interactive gestures in AnimatedLineGraph

    main

    To enable interactive scrubbing, set enablePanGesture={true}. When enabled, the graph responds to touch gestures, allowing users to move an indicator along the line.

    Gesture Configuration

    • enablePanGesture: Set to true to activate GestureDetector.
    • panGestureDelay: The delay (in ms) before the gesture becomes active (defaults to 300).
    • onGestureStart: Callback triggered when the gesture begins.
    • onGestureEnd: Callback triggered when the gesture ends.
    • onPointSelected: Callback triggered when the user's finger is over a specific data point.

    When a gesture is active, the SelectionDot (if provided) will follow the user's finger along the path.