TinyMCE for React
TinyMCE is a popular rich text editor used to add content-editing capabilities to web apps. When working with React, TinyMCE provides an official wrapper that makes integration quick and easy.
Here’s how to set it up in a React project:
1. Install the Package
Use npm:
npm install @tinymce/tinymce-react
2. Basic Usage
Import the component and render it:
import { Editor } from '@tinymce/tinymce-react';
function MyEditor() {
return (
<Editor
initialValue="<p>Start typing...</p>"
init={{
height: 300,
menubar: false,
plugins: 'link image code',
toolbar: 'undo redo | formatselect | bold italic | link image | code',
}}
/>
);
}
This will render a fully functional rich text editor inside your React component.
3. Handling Content Changes
You can capture changes to the editor content like this:
<Editor
onEditorChange={(newContent) => {
console.log(newContent); // Save or process the content here
}}
/>
Tips:
-
TinyMCE is highly customizable with plugins, themes, and custom toolbars.
-
You can host TinyMCE locally or use the cloud version.
-
It supports custom buttons, icons, and content filtering.
Learn More:
Visit TinyMCE React Docs for advanced configuration options.
If you're using TinyMCE in a React app and want to provide users with a way to remove all data-*
attributes from their content, you can create a custom toolbar button to do just that.
Why do this?
data-*
attributes are often added by frameworks, plugins, or tracking tools. In some cases, you might want to remove these before saving or publishing content, especially for clean, production-ready HTML.
How to Add the Button
You can use TinyMCE’s setup
function to add a custom button with a mop-like icon to your toolbar. Here's how:
import { Editor } from '@tinymce/tinymce-react';
function MyEditor({ content, contentChange, onEditorInit }) {
return (
<Editor
value={content}
onEditorChange={(newValue) => contentChange(newValue)}
onInit={onEditorInit}
init={{
height: 500,
menubar: false,
plugins: 'code',
toolbar: 'undo redo | mopCleaner | bold italic underline | code',
setup: (editor) => {
editor.ui.registry.addIcon('mopCleanerIcon', `
<svg width="24" height="24" viewBox="0 0 24 24">
<path d="M12 2v14" stroke="currentColor" stroke-width="2"/>
<path d="M8 16h8l1 4H7l1-4z" fill="currentColor"/>
</svg>
`);
editor.ui.registry.addButton('mopCleaner', {
icon: 'mopCleanerIcon',
tooltip: 'Remove all data-* attributes',
onAction: () => {
const currentContent = editor.getContent();
const cleanedContent = currentContent.replace(/\sdata-[\w-]+="[^"]*"/g, '');
editor.setContent(cleanedContent);
},
});
},
}}
/>
);
}
How it works:
- The button removes all HTML attributes that match the pattern
data-something="value"
. - It works even when multiple
data-*
attributes are in a single tag. - You can customize the icon or tooltip to match your app's style.
Tip:
To support edge cases, such as attributes with single quotes or no values, you can enhance the regex as needed.
Comments