Recently I worked in a project where I had to integrate the Swagger Editor with a React application.

But, due to lack of proper resources on how to do that, I had to dig into the code and identify how to use the editor components in our application. So, I though writing this small blog to tell you how could we do that.

Let’s start off with a basic react application.

npx create-react-app my-swagger-editor

Now, install the swagger-editor npm module.

npm install swagger-editor

Now, let’s create our editor. Open the App.js file in your application and add the following imports.

In the render() function, create an empty <div> with an id.

Then add the componentDidMount() function, add the following code.

We need to add necessary styles to our index.css file. Otherwise, embedded swagger-ui will not be able to scroll. :)

It is all set. Run your application with npm start. You will be able to see the swagger editor opens up.

Adding Some Functionality.

We have integrated the swagger editor with our app. We can do the changes that we want to the swagger file. But how could we get the updated content out of it?

The swagger editor has a built-in drop zone. Therefore, we do not need to add separate components to upload a swagger file. What I’m going to show you is how to get the modified content from the editor and do some thing useful with it.

The Swagger Editor uses the browser local storage to store the editor content. The content is stored with a key ‘swagger-editor-content’.

You can access it by,

window.localStorage.getItem(‘swagger-editor-content’);

Let’s modify our code by adding a button to save the swagger editor content.

In this example, I’m only logging the editor content to the console. But you can save it to a file, or send it to a remote service for storage etc depending on your requirement.

You can find the complete project in my github repository [1].

This is a very basic post to let you know how to integrate the swagger editor with your react application.

Hope you enjoy.

[1] https://github.com/menakaj/my-swagger-editor