0

Lets say my strategy calculates some numbered label. How can I pass this (e.g. via props) to the decorator component.

I know there is a props property in CompositeDecorator but how can I access it from the strategy function?

Obiwahn
  • 2,677
  • 2
  • 26
  • 36
  • `strategy function` search contents and determine when a `CompositeDecorator` should be created, that means the `CompositeDecorator` not exist when doing `strategy`. How you can access a property of a non-exits component. – Jiang YD Dec 24 '18 at 08:50

2 Answers2

0

I'm a bit new to DraftJs, but based on my understanding:

Strategies should be used to identify the range of text that need to be decorated. The rendering of that decoration (which presumably includes calculating what the label should be) should be handled in the component itself, rather than the strategy.

You should be able to access the ContentState via the props object in your component, and calculate the label from that. The constructor of your component could be a good place for executing the logic for calculating the label. This also means that you might have to use a class definition for your decorator components as opposed to a pure function as shown in the examples on the draftjs website.

Kartik
  • 160
  • 1
  • 7
0

You can also circumvent the issue by reading the values from the text with regex. The following example is done with @draft-js-plugins:

// How the section is detected.
const strategy = (contentBlock, callback) => {
  const text = contentBlock.getText();
  const start = text.indexOf('<_mytag ');
  const endTag = '/>';
  const end = text.indexOf(endTag);
  if (start !== -1 && end !== -1) {
    callback(start, end + endTag.length);
  }
};

// What is rendered for the detected section.
const component = ({ decoratedText }) => {
  if (decoratedText) {
    const label = decoratedText.match(/label="([a-zA-Z0-9/\s]*?)"/);
    if (
      label &&
      typeof label[1] === 'string'
    ) {
      return <div>{label[1]}</div>;
    }
    return null;
  }
};

export const MyTagPlugin = {
  decorators: [
    {
      strategy,
      component,
    },
  ],
};
ahoys
  • 31
  • 2