Home > database >  Beginner - Callback function after dangerouslySetInnerHTML
Beginner - Callback function after dangerouslySetInnerHTML

Time:12-22

I've just started learning react so I was wondering if there's a way to do this or even if it's the correct way of doing it.

I have in my App.js a component called DeckTable

return (
    <>
      <DeckTable decksCompared={decksCompared} sideboardsCompared={sideboardsCompared} decks={decks} headerCompared={headerCompared} />
    </>
)

In the DeckTable.js I'll use those values passed from the App.js and create a table concatenating strings and return it using dangerouslySetInnerHTML, like so:

var html = '<table>...</table>'
return <div dangerouslySetInnerHTML={{ __html: html }} />

Is this the best/correct way of doing it? If I need to call a function now after the table is rendered on the screen where/how would I do that?

If you guys need any more info, just ask.

Thank you so much.

CodePudding user response:

It easy to use and understand for beginner

function setDangerousHtml(html, el) {
        if (el === null) return;
        const range = document.createRange();
        range.selectNodeContents(el);
        range.deleteContents();
        el.appendChild(range.createContextualFragment(html));
}

// Your function for any HTML in react


// Usage Very Simple

<div type='link' ref={setDangerousHtml.bind(null,'<YOUR HTML CODE>')}>
</div>

CodePudding user response:

If you want DeckTable to return a table with the props you passed on App.js (decksCompared, sideboardsCompared, decks, and headerCompared) you can just return a div with a table that uses those props inside. You shouldn't need to use innerHTML.

  • Related