Issue
I would like to parse html generated with tinymce, modified by adding jsx, in react.
Example:
import Youtube from "react-youtube"
function Comment() {
return (
<div class="comment">
// I want something that can parse like this
{parse(`<p>
<code class="language-javascript">console.log("hi")</code>
<Youtube videoId="10"/>
<a href="https://youtu.be/stackoverflow">Youtube</a>
</p>`)}
</div>
)
}
I have come across react-jsx-parser, which doesn't work as expected :(
I have also tried converting html string to jsx string:
import parse from "html-react-parser";
import ReactElementToJsxString from "react-element-to-jsx-string";
import { parse as parsehtml } from "node-html-parser";
function modifycomment () {
const comment = ReactElementToJsxString(parse(`<p>
<code class="language-javascript">console.log("hi")</code>
<a href="https://youtu.be/stackoverflow">Youtube</a>
</p>`));
const link = parsehtml(comment).querySelector("a");
return comment.replace(link.toString(),
`<Youtube videoId="${link.getAttribute("href"),replace("https://youtu.be/", "")}"${link.toString()}`);;
}
Then parse it:
import Youtube from "react-youtube";
import JsxParser from "react-jsx-parser";
function Comment () {
return (
<div class="comment">
<JsxParser
components={{ Youtube }}
jsx={modifycomment()}
/>
</div>
)
}
which led to errors in rendering (something like the child to remove is not a child of this Node) :(
Solution
Based on react-youtube documentation you just need to pass the video Id. But your code has an extra <a> tag.
comment.replace(link.toString(),
`<Youtube videoId="${link.getAttribute("href"),replace("https://youtu.be/", "")}"${link.toString()}`);
and you are not assigning this to anything. I have made changes and did a sample one. Check this sandbox
By the way, I took some sample video
Answered By - mchowdam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.