Search code examples
cssreactjsdraftjs

Draft.js change default monospace font


By default Draft Editor uses the default system monospace. I was wondering if they was a way to change it to Consolas through Draft.css or using global css classes.


Solution

  • The root element of the editor component has DraftEditor-root class.

    enter image description here

    You can use this class name to specify styles this way:

    .DraftEditor-root {
      font-family: Consolas;
      // other styles thay you want:
      font-size: 24px;
      border: 1px solid black;
    }
    

    Check the demo below, In this example, I used "Arial" font-family, with "Consolas" it works similarly:

    const {Editor, EditorState, ContentState} = Draft;
    
    class Container extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          editorState: EditorState.createWithContent(ContentState.createFromText('Arial font-family'))
        };
      }
      
      _handleChange = (editorState) => {
        this.setState({ editorState });
      }
      
      render() {
        return (
          <Editor 
            placeholder="Type away :)"
            editorState={this.state.editorState}
            onChange={this._handleChange}
          />
        );
      }
    }
    
    ReactDOM.render(<Container />, document.getElementById('react-root'));
    .DraftEditor-root {
      font-family: Arial;
      font-size: 24px;
      border: 1px solid black;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.0/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.7.0/Draft.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/draft-js/0.10.0/Draft.js"></script>
    <div id="react-root"></div>