React Docgen

8.0.3 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `react-docgen` to parse a TypeScript React functional component, extracting its display name, description, and detailed prop information including types, descriptions, and default values.

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);
}

view raw JSON →