0

I am fetching HTML from my backend (generated by CKEditor) I am then using DangerouslySetInnerHTML to render said HTML like this :

 const parsed = DOMPurify.sanitize(album.description)
 <div dangerouslySetInnerHTML ={{ __html: parsed }} className={styles.albumDescription} </div>

It works fine and I'm able to render my HTML. However I'm having troubles with embed medias. CK editor returns the media link in a <oembed /> tag.

What I would like to do is that each time there is a <oembed />, insert them into <ReactPLayer /> component.

I understand I could probably use vanilla js DOM manipulation and use something like getElementsByTagName but I assume that's not great practice to do that in react.

2
  • 1
    " I assume that's not great practice to do that in react." So is using dangerouslySetInnerHTML Commented Jul 1, 2022 at 14:21
  • @Salketer. I sanitize my input, but how should I go about rendering my html without using dangerouslySetInnerHTML then ? Commented Jul 1, 2022 at 14:24

1 Answer 1

1

Using the DOM manipulation the challenge would be to verbatim replace all the attributes that <oembed .... /> would have, not impossible though.

If the incoming html string is not HUGE (running in several MBs), a simple string regex manipulation should do the trick:

Option 1: If you are sure that it'll always be <oembed ... />, then the following works.

const desc = album.description;
oembed_2_player = desc.replaceAll(/\<oembed ([^\/]*)\/\>/gi,"<ReactPLayer $1 />"); 
const parsed = DOMPurify.sanitize(oembed_2_player)
 <div dangerouslySetInnerHTML ={{ __html: parsed }} className={styles.albumDescription} </div>

Option 2: If you expect <oembed ....> ... & you want to translate it into <ReactPlayer ..same-as-in-oembed..> ..dito... then

const desc = album.description;
oembed_2_player = desc.replaceAll(/\<(oembed) ([^\>]*)\>([^\<]*)<\/\1\>/gi,"<ReactPLayer $2>$3</ReactPLayer>");
const parsed = DOMPurify.sanitize(oembed_2_player)
 <div dangerouslySetInnerHTML ={{ __html: parsed }} className={styles.albumDescription} </div>
 

Hope this helps 👍

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.