Swagger UI for React

5.32.4 · active · verified Wed Apr 22

swagger-ui-react is a specialized React component that seamlessly integrates Swagger UI directly into React applications. It exposes the full capabilities of Swagger UI through a simple React component, `SwaggerUI`. Unlike the core Swagger UI distribution, this package declares `react` and `react-dom` (versions >=16.8.0 <20) as peer dependencies, ensuring compatibility with existing React environments. The package's versioning closely mirrors the underlying Swagger UI, with the current stable release being 5.32.4. It receives frequent updates, including bug fixes, performance enhancements, and crucial security patches, as demonstrated by recent releases addressing several CVEs and introducing features like basic OpenAPI 3.2.0 support and dark mode. A notable aspect is the inclusion of anonymized installation analytics via Scarf, which users can easily opt out of through `package.json` settings or an environment variable. Developers should be mindful of specific prop behaviors, such as `layout` and `docExpansion` applying only on initial mount, and the mutual exclusivity of the `spec` and `url` props.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate `SwaggerUI` into a React component, loading an OpenAPI specification from a URL, applying initial documentation expansion settings, and including basic interceptor and completion callbacks. It also shows a common pattern for defining the API URL via environment variables.

import React from "react";
import SwaggerUI from "swagger-ui-react";
import "swagger-ui-react/swagger-ui.css";

const App = () => {
  const apiUrl = process.env.REACT_APP_SWAGGER_URL || "https://petstore.swagger.io/v2/swagger.json";
  const initialDocExpansion = "list"; // 'list', 'full', 'none'

  return (
    <div style={{ padding: '20px' }}>
      <h1>My API Documentation</h1>
      <SwaggerUI 
        url={apiUrl} 
        docExpansion={initialDocExpansion}
        requestInterceptor={(req) => {
          // Example: Add an authorization header
          // req.headers.Authorization = `Bearer ${someAuthToken}`;
          return req;
        }}
        onComplete={(system) => {
          console.log("Swagger UI finished rendering.", system);
        }}
      />
    </div>
  );
};

export default App;

view raw JSON →