Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Fragment to insert HTML rendered on the back end via dangerouslySetInnerHTML

I used to compile and insert JSX components via

<div key={ ID } dangerouslySetInnerHTML={ { __html: HTML } } />

which wrapped my HTML into a <div>:

<div>my html from the HTML object</div>

Now react > 16.2.0 has support for Fragments and I wonder if I can use that somehow to avoid wrapping my HTML in a <div> each time I get data from the back end.

Running

<Fragment key={ ID } dangerouslySetInnerHTML={ { __html: HTML } } />

will throw a warning

Warning: Invalid prop `dangerouslySetInnerHTML` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.
in React.Fragment

Is this supported yet at all? Is there another way to solve this?

Update

Created an issue in the react repo for it if you want to upvote it.

like image 876
Dominik Avatar asked Jan 13 '18 03:01

Dominik


1 Answers

Short Answer

Not possible:

key is the only attribute that can be passed to Fragment. In the future, we may add support for additional attributes, such as event handlers.

https://reactjs.org/docs/fragments.html

You may want to chime in and suggest this as a future addition.

https://github.com/facebook/react/issues

In the Meantime

You may want to consider using an HTML parsing library like:

https://github.com/remarkablemark/html-react-parser

Check out this example to see how it will accomplish your goal:

http://remarkablemark.org/blog/2016/10/07/dangerously-set-innerhtml-alternative/

In Short

You'll be able to do this:

<>
{require('html-react-parser')(
    '<em>foo</em>'
)}
</>
like image 193
Jonny Asmar Avatar answered Sep 22 '22 13:09

Jonny Asmar