How to use draft js in react js?
December 21, 2024Hi Friends 👋,
Welcome To aHoisting!
To use draft js you have to import draft js
from Draft.js
and react-draft-wysiwyg
packages that’s how you can use draft js in react js.
Today, I am going to show you, how to use draft js in react js.
Installation
Install the following packages to use draft js in react js.
npm
npm install draft-js react-draft-wysiwyg
yarn
yarn add draft-js react-draft-wysiwyg
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Let’s start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React, { useState } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
Step 3: Create a Component.
You can use <Editor/>
to use draft js in react js.
<div className="App">
<header className="App-header">
Rich Text Editor Example
</header>
<Editor
editorState={editorState}
onEditorStateChange={setEditorState}
/>
</div>
Use draft js example.
The below code is an example of a React. You have to import draft js
from 'draft-js'
and 'react-draft-wysiwyg'
that’s how you can use draft js in react js.
App.js
import React, { useState } from 'react';
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
function App() {
const [editorState, setEditorState] = useState(
() => EditorState.createEmpty(),
);
return (
<div className="App">
<header className="App-header">
Rich Text Editor Example
</header>
<Editor
editorState={editorState}
onEditorStateChange={setEditorState}
/>
</div>
)
}
export default App;
In the above code example, I have used the 'react-draft-wysiwyg'
to use draft js in react js.
Check the output of the above code.
All the best 👍