Skip to content

rickhanlonii/draftjs-md-converter

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

62 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Build Status npm version

Draft.js to Markdown to Draft.js converter

Converts content from Draft.js blocks to Markdown and vice versa.

Reasoning and background

This exists because I needed a highly customisable rich text editor which posts to an external API in Markdown. Draft.js to the rescue! Alas, it doesn't ship with any sort of import or export to or from markdown so I've written my own.

Installation

npm install draftjs-md-converter

Support

The following inline styles are supported:

  • bold
  • italic
  • H1 - H6

The following block syles are supported:

  • ordered list
  • unordered list
  • block quote

The following media is supported:

  • images

Usage

mdToDraftjs(markdown: String): RawDraftContentState

Use convertToRaw from the draft-js library to convert the resulting RawDraftContentState into a draft-js ContentState.

draftjsToMd(rawData: RawDraftContentState): String

Use convertFromRaw from the draft-js library to get the raw RawDraftContentState to then pass into the converter.

Custom dictionaries

The default Markdown dictionary is

{
  BOLD: '__',
  ITALIC: '*'
};

This can be extended or overridden by passing it in as a second optional argument to draftjsToMd, e.g.

const myMdDict = {
  BOLD: '**',
  STRIKETHROUGH: '~~'
};
const markdown = draftjsToMd(blocks, myMdDict)

Example

[---]

import { mdToDraftjs, draftjsToMd } from 'draftjs-md-converter';
import { EditorState, ContentState, convertToRaw, convertFromRaw } from 'draft-js';

[---]

constructor(props) {
  super(props);

  // some default value in markdown
  const defaultValue = this.props.defaultValue;
  const rawData = mdToDraftjs(defaultValue);
  const contentState = convertFromRaw(rawData);
  const newEditorState = EditorState.createWithContent(contentState);

  this.state = {
    editorState: newEditorState,
  };
  this.onChange = (editorState) => {
    this.props.onChange(this.getMarkdown());
    this.setState({ editorState });
  };
}

[---]

getMarkdown() {
  const content = this.state.editorState.getCurrentContent();
  return draftjsToMd(convertToRaw(content));
}

[---]

Run tests

npm test

Run tests with a watcher

npm run test-dev

Lint

npm run lint

About

Converts content from Draft.js blocks to Markdown and vice versa.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 100.0%