> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.knapsack.cloud/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.knapsack.cloud/_mcp/server.

# React

Knapsack for React works by scanning your specified React code locations and automatically discovering reusable components, making them instantly available in your design system.

**Why This Approach:**

* ⚡ **Zero Manual Work** - Knapsack finds and configures your components automatically
* 🔄 **Always Current** - Your documentation stays in sync with code changes
* 🎯 **Intelligent** - Understands different export patterns and component structures
* 🚀 **Scale Effortlessly** - Handle hundreds of components without individual setup

## Requirements

* **React 18 or 19**
* **Knapsack 4.89.4+**

Knapsack uses your React, not its own. `react` and `react-dom` go in `dependencies`.

***

## Install

```bash
npm install @knapsack/renderer-react
```

## Configure

**Minimal Setup**
The simplest configuration requires just specifying where your React components are located:

```js
// knapsack.config.js
const { KnapsackReactRenderer } = require('@knapsack/renderer-react');

module.exports = configureKnapsack({
  templateRenderers: [
    new KnapsackReactRenderer({
      codeSrcs: [{ path: './src/components/**/*.tsx' }],
    }),
  ],
};
```

**Full Configuration Example**
Here's a comprehensive example showing all available options:

```js
const { KnapsackReactRenderer } = require('@knapsack/renderer-react');

module.exports = configureKnapsack({
  templateRenderers: [
    new KnapsackReactRenderer({
      // Code discovery paths
      codeSrcs: [
        { path: '@my-design-system/react' },
        { path: './src/components/**/*.{tsx,jsx}' },
        {
          path: '@mui/material/*',
          filter: (path) => !path.includes('internal'),
        },
      ],

      // React Strict Mode
      disableReactStrictMode: true,

      // Demo wrapper for all components
      demoWrapperPath: './src/demo-wrapper.tsx',

      // Webpack customization
      webpackConfig: {
        resolve: {
          alias: {
            '@': path.resolve(__dirname, 'src'),
          },
        },
        module: {
          rules: [
            {
              test: /\\.module\\.css$/,
              use: ['style-loader', 'css-loader'],
            },
          ],
        },
      },
    }),
  ],
};
```

### Code Sources

The **codeSrcs** array tells Knapsack where to find your React components and how to process them. The renderer will scan these paths, find React component exports, and make them available in the Knapsack UI for documentation and demos.

##### Local Components

Paths are relative to *knapsack.config.js*

```js
codeSrcs: [
  // Specific directory
  { path: './src/components/**/*.tsx' },

  // Multiple file extensions
  { path: './src/ui/**/*.{tsx,jsx,ts,js}' },

  // Specific component types
  { path: './src/components/atoms/*.tsx' },
  { path: './src/components/molecules/*.tsx' },
];
```

##### External Libraries

Ensure that any external library is included in your package dependencies

```js
codeSrcs: [
  // Entire package
  { path: '@radix-ui/themes' },
  { path: '@chakra-ui/react' },

  // Package sub-paths
  { path: '@mui/material/*' },
  { path: '@my-org/design-system/components/*' },
];
```

##### Smart Filtering

Use filters to control exactly which components are discovered:

```js
codeSrcs: [
  {
    path: './src/**/*.tsx',
    filter: (path) => {
      // Only include components, exclude utilities and tests
      return (
        path.includes('/components/') &&
        !path.includes('.test.') &&
        !path.includes('.stories.')
      );
    },
  },
  {
    path: '@mui/material/*',
    filter: (path) => {
      // Exclude problematic MUI exports
      const excludedPaths = [
        '@mui/material/index',
        '@mui/material/styles/index',
        '@mui/material/utils',
      ];
      return !excludedPaths.some((excluded) => path.includes(excluded));
    },
  },
];
```

### Demo Wrapper

A demo wrapper is a React component that wraps around each of your components when they're rendered in Knapsack. This is essential for providing context like theme providers, CSS resets, or global styles.

Additionally, the ***props*** contain useful information beyond just ***props.children*** for your custom usage: ***props.pattern***, ***props.template***, ***props.demo***, and ***props.patternsUsed***. See the TypeScript definition for more details.

##### Setup

**1. Create a Wrapper:**
Create a file (e.g., src/demo-wrapper.tsx):

```tsx
import React from 'react';
import { ThemeProvider } from 'styled-components';
import { theme } from './theme';
import './global-styles.css';

interface DemoWrapperProps {
  children: React.ReactNode;
}

export const DemoWrapper: React.FC<DemoWrapperProps> = ({ children }) => {
  return (
    <ThemeProvider theme={theme}>
      <div className="demo-wrapper">{children}</div>
    </ThemeProvider>
  );
};
```

**2. Add your Wrapper Path**
Reference your wrapper in the renderer configuration:

```js
new KnapsackReactRenderer({
  demoWrapperPath: './src/demo-wrapper.tsx',
  codeSrcs: [
    // your code sources
  ],
});
```

##### Common Examples

```tsx
// 1. Theme Provider Wrapper
import { ThemeProvider } from '@my-org/theme';
import { defaultTheme } from './themes';

export const DemoWrapper = ({ children }) => (
  <ThemeProvider theme={defaultTheme}>{children}</ThemeProvider>
);

// 2. CSS-in-JS Provider
import { ChakraProvider } from '@chakra-ui/react';
import { theme } from './chakra-theme';

export const DemoWrapper = ({ children }) => (
  <ChakraProvider theme={theme}>{children}</ChakraProvider>
);

// 3. Multiple Providers
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'styled-components';
import { theme } from './theme';

const queryClient = new QueryClient();

export const DemoWrapper = ({ children }) => (
  <QueryClientProvider client={queryClient}>
    <ThemeProvider theme={theme}>
      <div className="demo-container">{children}</div>
    </ThemeProvider>
  </QueryClientProvider>
);
```

### React Strict Mode

By default, react strict mode is enabled. If you need to disable React Strict mode for your components, you can set this option to ***true*** in the configuration:

```js
// knapsack.config.js
const { KnapsackReactRenderer } = require('@knapsack/renderer-react');

module.exports = configureKnapsack({
  templateRenderers: [
    new KnapsackReactRenderer({
      disableReactStrictMode: true,
    }),
  ],
};
```

### Webpack Configuration

The React renderer uses Webpack under the hood to process your components. You can provide custom webpack configuration to handle React-specific requirements like babel-loader, JSX transformation, and other build tools.

These webpack configurations are your responsibility to implement correctly. Knapsack provides the integration but you handle the webpack setup.

##### Common Use Cases

You might need to configure webpack for:

* **Path aliases** - Create import shortcuts like `@/components/Button`
* **CSS processing** - Handle CSS modules, SCSS, styled-components, etc.
* **Asset handling** - Process images, fonts, and other static files
* **TypeScript configuration** - Set up TypeScript compilation and path mapping
* **Third-party library compatibility** - Configure loaders for specific libraries

##### Common Examples

**Path Aliases**

```js
webpackConfig: {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@utils': path.resolve(__dirname, 'src/utils')
    }
  }
}
```

**CSS Modules**

```js
webpackConfig: {
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
      '@components': path.resolve(__dirname, 'src/components'),
      '@utils': path.resolve(__dirname, 'src/utils')
    }
  }
}
```

**SCSS Support**

```js
webpackConfig: {
  module: {
    rules: [
      {
        test: /\\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
      },
    ];
  }
}
```

**Asset Handling**

```js
webpackConfig: {
  module: {
    rules: [
      {
        test: /\\.(png|jpg|gif|svg)$/,
        type: 'asset/resource',
      },
      {
        test: /\\.(woff|woff2|eot|ttf|otf)$/,
        type: 'asset/resource',
      },
    ];
  }
}
```

**TypeScript Path Mapping**

```js
webpackConfig: {
  resolve: {
    alias: {
      // Map tsconfig paths
      '@/*': path.resolve(__dirname, 'src/*'),
      '@components/*': path.resolve(__dirname, 'src/components/*')
    }
  }
}
```