React Docgen
React Docgen is a library designed to extract information from React components, primarily for the purpose of generating documentation. It parses React component source code to identify prop types, default props, method definitions, and other relevant metadata, which can then be used by documentation tools or style guides. The current stable version is 8.0.3. The project maintains an active development pace, with frequent patch releases addressing bug fixes and minor improvements, while major versions primarily update Node.js compatibility. Its key differentiator is its direct association with the React ecosystem, offering robust AST parsing specifically tailored for React components, including support for various component definition patterns and TypeScript types.
Common errors
-
Error: Cannot find module 'react-docgen'
cause The `react-docgen` package is either not installed, or you are trying to import it using CommonJS `require()` in an ESM context (or vice-versa) without proper configuration or tooling.fixEnsure `react-docgen` is installed (`npm install react-docgen` or `yarn add react-docgen`). For ESM projects, use `import { parse } from 'react-docgen';`. If using CommonJS, check your `tsconfig.json` or bundler settings for module resolution. -
SyntaxError: Unknown type: VoidPattern
cause This error occurs when `react-docgen` encounters a newer JavaScript syntax feature (like a `VoidPattern`) that it doesn't recognize. This was a known issue fixed in `react-docgen@8.0.1`.fixUpdate `react-docgen` to version 8.0.1 or newer (`npm update react-docgen` or `yarn upgrade react-docgen`). -
Error: No component definition found for ...
cause The parser could not identify any React component definition within the provided source code using the default resolvers. This can happen with unusual export patterns, higher-order components (HOCs) not explicitly handled, or incorrect file paths/content.fixVerify that your component is defined and exported in a way `react-docgen` can understand (e.g., `export default function MyComponent`, `export const MyComponent = () => {}`). Consider using `parseWithCustomResolvers` and providing a custom resolver function if your component definition pattern is non-standard.
Warnings
- breaking Version 8.0.0 of `react-docgen` dropped support for Node.js 16, 17, 18, 19, and 21. Users must upgrade to Node.js 20.9.0 or newer 20.x versions, or Node.js 22.0.0 or any newer version.
- gotcha Parsing complex or highly dynamic React component patterns (e.g., HOCs, render props within highly nested structures, or non-standard component definitions) might not yield complete or accurate results with default resolvers and handlers. Custom resolvers and handlers may be required.
- gotcha As of the provided package metadata, the official `README.md` for `react-docgen` was not available. Users might need to consult the GitHub repository directly for comprehensive usage examples, advanced configuration, and a full understanding of the API.
- gotcha `react-docgen` primarily works with static analysis of component code. It does not execute components or rely on runtime introspection, meaning runtime-only prop definitions or dynamically generated props will not be detected.
Install
-
npm install react-docgen -
yarn add react-docgen -
pnpm add react-docgen
Imports
- parse
const { parse } = require('react-docgen');import { parse } from 'react-docgen'; - parseWithCustomResolvers
import parseWithCustomResolvers from 'react-docgen/lib/parseWithCustomResolvers';
import { parseWithCustomResolvers } from 'react-docgen'; - handlers
const handlers = require('react-docgen').handlers;import { handlers } from 'react-docgen'; - resolver.findAllExportedComponentDefinitions
import { findAllExportedComponentDefinitions } from 'react-docgen/dist/resolver';import { resolver } from 'react-docgen'; const componentResolver = resolver.findAllExportedComponentDefinitions; - DocgenResult
import { DocgenResult } from 'react-docgen';import type { DocgenResult } from 'react-docgen';
Quickstart
import { parse, resolver, handlers } from 'react-docgen';
import path from 'path';
const componentSource = `
/**
* A button component for user interaction.
*/
interface ButtonProps {
/**
* The text content of the button.
*/
label: string;
/**
* Callback fired when the button is clicked.
*/
onClick?: (event: React.MouseEvent<HTMLButtonElement>) => void;
/**
* Whether the button is disabled.
* @default false
*/
disabled?: boolean;
}
function Button({ label, onClick, disabled = false }: ButtonProps) {
return (
<button onClick={onClick} disabled={disabled}>
{label}
</button>
);
}
export default Button;
`;
try {
const results = parse(
componentSource,
resolver.findAllExportedComponentDefinitions,
Object.values(handlers),
{ filename: 'Button.tsx' }
);
if (results.length > 0) {
const doc = results[0];
console.log(`Component Name: ${doc.displayName}`);
console.log(`Description: ${doc.description}`);
console.log('Props:');
for (const propName in doc.props) {
const prop = doc.props[propName];
console.log(` - ${propName}: ${prop.description} (Type: ${prop.type?.name}, Required: ${prop.required}, Default: ${prop.defaultValue?.value})`);
}
} else {
console.log('No component definition found.');
}
} catch (error) {
console.error('Error parsing component:', error);
}