logo
Published on

Simple Code Editor in SPFx Web Part

This article provides steps to implement a Simple Code Editor in the SharePoint Framework (SPFx) web part using Ace Editor.
This lightweight editor enables users to edit and preview code directly inside SharePoint modern pages.


⚙️ Install Dependencies

Install Ace Editor and PnP JS dependencies:

npm install @pnp/sp --save
npm install react-ace ace-builds --save

🧩 Update the React Component

Open your web part component (e.g. SpfxReactCodeeditor.tsx) and replace it with the following implementation:

import * as React from 'react';
import styles from './SpfxReactCodeeditor.module.scss';
import { ISpfxReactCodeeditorProps } from './ISpfxReactCodeeditorProps';
import AceEditor from "react-ace";

import 'ace-builds/src-noconflict/mode-javascript';
import 'ace-builds/src-noconflict/theme-github';

export interface ISpfxReactCodeeditorState {
  code: string;
}

export default class SpfxReactCodeeditor extends React.Component<ISpfxReactCodeeditorProps, ISpfxReactCodeeditorState> {
  constructor(props: ISpfxReactCodeeditorProps) {
    super(props);
    this.state = { code: '' };
  }

  public render(): React.ReactElement<ISpfxReactCodeeditorProps> {
    return (
      <div className={styles.spfxReactCodeeditor}>
        <AceEditor
          placeholder="Type your code here..."
          mode="javascript"
          theme="github"
          name="codeEditor"
          width="100%"
          height="400px"
          fontSize={14}
          value={this.state.code}
          onChange={(value) => this.setState({ code: value })}
          showPrintMargin={true}
          showGutter={true}
          highlightActiveLine={true}
          setOptions={{
            enableBasicAutocompletion: true,
            enableLiveAutocompletion: true,
            enableSnippets: true,
            showLineNumbers: true,
            tabSize: 2
          }}
        />
      </div>
    );
  }
}

⚙️ Configure the SPFx Context

In your main file, configure PnP JS context for SharePoint operations (if needed):

sp.setup({ spfxContext: this.props.context });

🧠 Create the Interface

In ISpfxReactCodeeditorProps.ts, define your interface:

export interface ISpfxReactCodeeditorProps {
  description: string;
}

🚀 Build and Deploy the Solution

Build, bundle, and deploy your SPFx web part with the following commands:

gulp build
gulp bundle --ship
gulp package-solution --ship

Then upload the generated .sppkg file from the sharepoint/solution folder to your App Catalog.
Deploy the package and add the web part to a modern SharePoint page.


📂 GitHub Sample Project

View full SPFx project on GitHub:Simple Code Editor in SPFx Web Part

GitHub

✅ Summary

This SPFx web part provides a quick way to embed a simple code editor inside SharePoint using React Ace Editor.
It supports syntax highlighting, autocompletion, snippets, and other basic features suitable for lightweight code editing tasks.

Calendar IconBook a demo