Hello,
Recently I was working on POC for rich text editor using React-Draft-Wysiwyg editor.
There we have a requirement to add find & replace dialog box which should find the matching text from all the blocks and height it with background color. For the POC we added find text functionality. Here in this blog I will explain how to do it.
For this I have created separate React component and add it as custom option to editor toolbar. Let's understand it step by step.
If you want to know how to add custom option you can find reference from here.
https://jpuri.github.io/react-draft-wysiwyg/#/docs
1) Create Modal with Text input and Button
Please note I have used grommet UI library to build the POC. So text input and button was imported from Grommet.
<TextInput
data-cy="find-text"
autoFocus
onChange={this.onChangeFindText}
value={this.state.findText}
/>
<Button
id="find"
label="Find"
onClick={this.onFindClick}
/>
2) Handle Find Click Event
onFindClick = () => {
const search = this.state.findText;
let contentState = convertToRaw(this.props.editorState.getCurrentContent());
contentState.blocks.forEach(block => {
const text = block.text;
const matches = [...text.matchAll(search)];
if(matches.length > 0) {
matches.forEach(match =>{
block.inlineStyleRanges.push({length: match[0].length,
offset: match.index,
style: "bgcolor-rgb(247,218,100)"
})
});
}
});
let newEditorState = {
editorState: EditorState.createWithContent(convertFromRaw({blocks: contentState.blocks,entityMap: {}})),
contentState: null
}
this.props.onChange(EditorState.createWithContent(convertFromRaw({blocks: contentState.blocks,entityMap: {}})));
}
In above code we are getting search text from the state and matching it with texts of all custom blocks. Where ever it matches we are setting inline styles in blocks with yellow color background. and then setting state of editor again with new blocks.
Hope this helps you.
No comments:
Post a Comment