Get started with Draft.js
This short get started guide will help you get started with Draft.js. The main objective will be that after this guide you will have an text editor in a React app, where you can open a template article.
For the sake of this tutorial we're going to use
create-react-app app to
If you do not have that installed it can be installed with:
Create the editor application
Start by creating a new React application using create-react-app
When the install script is completed your React app should be ready to run. Now we need to install Draft.js as well.
(React and React-dom is already installed in the previous step)
Start the application
We can now try to run the React application. Type
npm start in the CLI to start the development server
When the dev server is started you should be able to open you React app by navigation to http://localhost:3000
Now it's the time to open the source code to your project in one of your text editors. You will notice there are some folders and files already created for you by the create-react-app.
In our case we will just go ahead and use the created components. Start by opening
The first step will be to remove some boilerplate code and replace it with the Draft.js Editor. I removed everything in div.App, I also changed the className property to blog-editor, after these changes my App.js looks like this.
In the next step we will import
Editor and EditorState from Draft.js, so at the top of the file we add
the following import statement
Then, in the render method, we add the
Editor component and pass the
editorState and onChange method as props.
Notice that we are passing
this.state.editorState and not just the imported EditorState.
This means that our App.js has it's own state containing the editorState. The initials setup is done in the constructor.
We also specify an
onChange method and passing as props.
This method is triggered by Draft.js Editor and in our case it will just replace
the old editorState with a new fresh one.
If you haven't, start the dev server with
and open localhost:3000
Congratulations, you now have an Draft.js editor up and running.