How to customize the link in DraftJS?
Azilen Technologies, azilen-logo
 Software Development
  by Chetan Buddh  December 29, 2021

How to customize the link in DraftJS?

Feature Image

One of the well-known rich text editor packages is DraftJS. You can configure it as per your needs. Recently, in one of our projects I came across one challenge of enriching the hyperlink feature of the editor. By default, it allows you to add a hyperlink, but in case you need to edit the same hyperlink, you need to remove the text, add the text and then attach the link. It is for sure not a good user experience. We wanted to provide the way Google provides users with the popup as shown in the below image.

Why Entity?

You cannot manage a lot of data without having a proper object. Thus, we need one such object which represents the metadata for a range of text within a Draft editor and that object is called Entity. It has three properties:

  •  type: A string that indicates what kind of entity it is, e.g. ‘LINK’, ‘MENTION’, ‘PHOTO’.
  • mutability: Not to be confused with immutability a la immutable-js, this property denotes the behaviour of a range of text annotated with this entity object when editing the text range within the editor.
  •  data: An optional object containing metadata for the entity. For instance, a ‘LINK’ entity might contain a data object that contains the href value for that link.

Using decorators or custom block components, you can add rich rendering to your editor based on entity metadata.

In the below snippet we override the default rendering.

Conclusion:

It is always better to explore the library you are using before jumping onto the custom solutions. Initially, we achieved the same task through vanilla JavaScript but then faced difficult scenarios like How can we manage editing hyperlinks? and How we can add hyperlink it into the editor? But the decorator plugin from DraftJS helped us out.

Come Partner With Azilen

We serve consultation from small and medium start-ups to veteran product owners with our Pro-360 Approach, which is adapted to your product and business!