CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-react-konva

React binding to canvas element via Konva framework providing declarative and reactive canvas graphics.

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

Configuration and utility functions for customizing React Konva behavior, accessing the reconciler, and managing rendering modes.

Capabilities

Strict Mode Configuration

Function to enable or disable strict mode for property updates, affecting how React Konva handles prop changes and validation.

/**
 * Configure strict mode for property updates
 * Controls validation and update behavior for Konva node properties
 * @param useStrictMode - Enable or disable strict mode
 */
var useStrictMode: (useStrictMode: boolean) => void;

Usage Examples:

import React from 'react';
import { Stage, Layer, Rect, useStrictMode } from 'react-konva';

// Enable strict mode for better property validation
const StrictModeExample = () => {
  React.useEffect(() => {
    // Enable strict mode at application startup
    useStrictMode(true);
    
    return () => {
      // Disable strict mode on cleanup (optional)
      useStrictMode(false);
    };
  }, []);

  return (
    <Stage width={800} height={600}>
      <Layer>
        <Rect x={100} y={100} width={100} height={100} fill="red" />
      </Layer>
    </Stage>
  );
};

// Conditional strict mode based on environment
const ConditionalStrictMode = () => {
  React.useEffect(() => {
    // Enable strict mode only in development
    const isDevelopment = process.env.NODE_ENV === 'development';
    useStrictMode(isDevelopment);
  }, []);

  return (
    <Stage width={800} height={600}>
      <Layer>
        <Rect x={50} y={50} width={200} height={150} fill="blue" />
      </Layer>
    </Stage>
  );
};

React Reconciler Access

Direct access to the React reconciler instance used by React Konva for advanced use cases and integration with other libraries.

/**
 * React reconciler instance for Konva integration
 * Provides low-level access to the reconciler for advanced use cases
 */
var KonvaRenderer: ReactReconciler.Reconciler<any, any, any, any, any, any>;

Usage Examples:

import React from 'react';
import { KonvaRenderer } from 'react-konva';
import Konva from 'konva';

// Advanced: Manual container management
const ManualContainerExample = () => {
  const containerRef = React.useRef(null);
  const fiberRootRef = React.useRef(null);

  React.useEffect(() => {
    // Create a Konva stage manually
    const stage = new Konva.Stage({
      container: containerRef.current,
      width: 400,
      height: 300
    });

    // Create a reconciler container
    fiberRootRef.current = KonvaRenderer.createContainer(
      stage,
      0, // ConcurrentRoot
      null,
      false,
      null,
      '',
      console.error,
      console.error,
      console.error,
      null
    );

    // Render React elements into the Konva stage
    KonvaRenderer.updateContainer(
      React.createElement('Layer', {}, [
        React.createElement('Rect', {
          key: 'rect',
          x: 50,
          y: 50,
          width: 100,
          height: 100,
          fill: 'green'
        })
      ]),
      fiberRootRef.current,
      null,
      () => console.log('Rendered')
    );

    return () => {
      // Cleanup
      KonvaRenderer.updateContainer(null, fiberRootRef.current, null);
      stage.destroy();
    };
  }, []);

  return <div ref={containerRef} />;
};

// Integration with external libraries
const ExternalLibraryIntegration = () => {
  React.useEffect(() => {
    // Example: Integrating with a state management library
    const unsubscribe = someStateManager.subscribe((state) => {
      // Use KonvaRenderer to update canvas based on external state
      const elements = state.canvasElements.map(el => 
        React.createElement(el.type, { key: el.id, ...el.props })
      );
      
      // Update the reconciler with new elements
      // This would typically be done within a proper React component
      console.log('External state changed:', elements);
    });

    return unsubscribe;
  }, []);

  return null; // This component doesn't render directly
};

Version Information

Access to the React Konva library version string for debugging and compatibility checks.

/**
 * React Konva library version string
 * Useful for debugging and compatibility checks
 */
var version: string;

Usage Examples:

import React from 'react';
import { version } from 'react-konva';

// Display version information
const VersionInfo = () => {
  React.useEffect(() => {
    console.log('React Konva version:', version);
    
    // Version compatibility check
    const [major, minor, patch] = version.split('.').map(Number);
    if (major < 18) {
      console.warn('This application requires React Konva v18 or higher');
    }
    
    // Feature detection based on version
    const hasNewFeatures = major >= 19;
    if (hasNewFeatures) {
      console.log('New React 19 features are available');
    }
  }, []);

  return (
    <div style={{ padding: '10px', fontSize: '12px', color: '#666' }}>
      React Konva v{version}
    </div>
  );
};

// Runtime version checks
const VersionChecks = () => {
  const [versionInfo, setVersionInfo] = React.useState(null);

  React.useEffect(() => {
    // Parse version information
    const [major, minor, patch] = version.split('.').map(Number);
    
    setVersionInfo({
      full: version,
      major,
      minor,
      patch,
      isSupported: major >= 18,
      hasReact19Support: major >= 19
    });
  }, []);

  if (!versionInfo) return null;

  return (
    <div>
      <h3>Version Information</h3>
      <ul>
        <li>Version: {versionInfo.full}</li>
        <li>Supported: {versionInfo.isSupported ? 'Yes' : 'No'}</li>
        <li>React 19 Support: {versionInfo.hasReact19Support ? 'Yes' : 'No'}</li>
      </ul>
    </div>
  );
};

Development Tools Integration

React Konva automatically integrates with React DevTools for debugging and inspection.

Usage Examples:

import React from 'react';
import { Stage, Layer, Rect } from 'react-konva';

// Component that can be inspected in React DevTools
const DebuggableComponent = () => {
  const [rectProps, setRectProps] = React.useState({
    x: 100,
    y: 100,
    width: 100,
    height: 100,
    fill: 'red'
  });

  // This state will be visible in React DevTools
  React.useEffect(() => {
    // DevTools will show this component and its state
    console.log('Component rendered with props:', rectProps);
  }, [rectProps]);

  const handleClick = () => {
    setRectProps(prev => ({
      ...prev,
      fill: prev.fill === 'red' ? 'blue' : 'red'
    }));
  };

  return (
    <Stage width={800} height={600}>
      <Layer>
        <Rect
          {...rectProps}
          onClick={handleClick}
          // These props will be visible in DevTools
          name="debuggable-rect"
          id="rect-1"
        />
      </Layer>
    </Stage>
  );
};

// Performance monitoring
const PerformanceMonitored = () => {
  React.useEffect(() => {
    // Performance marks for debugging
    performance.mark('react-konva-render-start');
    
    return () => {
      performance.mark('react-konva-render-end');
      performance.measure(
        'react-konva-render',
        'react-konva-render-start',
        'react-konva-render-end'
      );
    };
  });

  return (
    <Stage width={800} height={600}>
      <Layer>
        <Rect x={50} y={50} width={100} height={100} fill="green" />
      </Layer>
    </Stage>
  );
};

Component Ref Utilities

While not directly exported utilities, React Konva components provide standardized methods for accessing underlying Konva instances.

/**
 * Standard methods available on all Konva node component refs
 * Provides access to underlying Konva instances
 */
interface KonvaNodeComponent<Node extends Konva.Node, Props> {
  /**
   * Get the public Konva node instance
   * @returns The underlying Konva node
   */
  getPublicInstance(): Node;
  
  /**
   * Get the native Konva node instance
   * @returns The native Konva node
   */
  getNativeNode(): Node;
}

Usage Examples:

import React, { useRef } from 'react';
import { Stage, Layer, Circle } from 'react-konva';

// Accessing Konva instances through refs
const RefUtilityExample = () => {
  const circleRef = useRef(null);
  const stageRef = useRef(null);

  const handleButtonClick = () => {
    if (circleRef.current) {
      // Access the underlying Konva circle
      const konvaCircle = circleRef.current;
      
      // Use Konva methods directly
      konvaCircle.to({
        scaleX: 2,
        scaleY: 2,
        duration: 0.5,
        onFinish: () => {
          konvaCircle.to({
            scaleX: 1,
            scaleY: 1,
            duration: 0.5
          });
        }
      });
    }
  };

  const exportImage = () => {
    if (stageRef.current) {
      // Export stage as image
      const dataURL = stageRef.current.toDataURL();
      
      // Create download link
      const link = document.createElement('a');
      link.download = 'canvas-export.png';
      link.href = dataURL;
      link.click();
    }
  };

  return (
    <div>
      <button onClick={handleButtonClick}>Animate Circle</button>
      <button onClick={exportImage}>Export Image</button>
      
      <Stage ref={stageRef} width={800} height={600}>
        <Layer>
          <Circle
            ref={circleRef}
            x={200}
            y={200}
            radius={50}
            fill="purple"
          />
        </Layer>
      </Stage>
    </div>
  );
};

Install with Tessl CLI

npx tessl i tessl/npm-react-konva

docs

core-components.md

index.md

interactions.md

shapes.md

utilities.md

tile.json