0

I am trying to apply a format to the selected text, but the apply format method of gutenberg doesnt return any error and fails silently.

I am registering my format type like this

import { registerFormatType } from "@wordpress/rich-text";

registerFormatType(BLOCK_NAME, {
          title: "Answer",
          tagName: "span",
          className: SOME_CLASS
        });

and trying to apply like this

    on(SOME_EVENT, result => {
    applyFormat(props.value, { type: BLOCK_NAME });
}

The applyformat method doesn't throw any errors but when i try to apply the format to the text selection it didnt create the wrapper around it.It fails silently, any reason why its not working?

Update: I did a console.log on result from apply format, but it didnt return the formatted text.

const result = applyFormat(props.value, { type: BLOCK_NAME });
console.log(result)

props.value in console

{formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11}

value of result from applyFormat

{formats: Array(16), text: "qwe qwewq eqweq?", start: 4, end: 11}

I expect the applyFormat to add a span with a class name around the selected text, what am i doing wrong in the code?

3
  • Can you expand your code snippets to include more? It's unclear how/where you're calling applyFormat. By trying to hide what you're doing you've made it too generic
    – Tom J Nowell
    Feb 21 '20 at 10:55
  • @TomJNowell I am calling it inside a event handler, which i can assure getting triggered ( i didnt hide it intentionally, i just wanted to provide a mwe (stackoverflow.com/help/minimal-reproducible-example)), i am adding some data again to the post.
    – Naveen
    Feb 21 '20 at 11:36
  • 1
    @TomJNowell added some more details to the snippet.
    – Naveen
    Feb 21 '20 at 11:47
0

You won't see applied format in result's text attribute, however your result should have new activeFormats attribute. To get HTML with applied formats you can use wp.richText.toHTMLString({result}). This answer might help with some ideas.

0

Alright, after 5 hrs i have learnt this, you need to call applyFormat inside the props.onChange method, so the code would look like this

props.onChange( applyFormat(props.value, { type: BLOCK_NAME }) );

if you didnt execute the applyformat inside this props.onChange, no error would be thrown, but it would fail silently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.