score:70
You could leverage the html-to-react
npm module.
Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.
score:2
I needed to use a link with onLoad attribute in my head where div is not allowed so this caused me significant pain. My current workaround is to close the original script tag, do what I need to do, then open script tag (to be closed by the original). Hope this might help someone who has absolutely no other choice:
<script dangerouslySetInnerHTML={{ __html: `</script>
<link rel="preload" href="https://fonts.googleapis.com/css?family=Open+Sans" as="style" onLoad="this.onload=null;this.rel='stylesheet'" crossOrigin="anonymous"/>
<script>`,}}/>
score:3
Here's a little less opinionated version of the RawHTML function posted before. It lets you:
- configure the tag
- optionally replace newlines to
<br />
's - pass extra props that RawHTML will pass to the created element
- supply an empty string (
RawHTML></RawHTML>
)
Here's the component:
const RawHTML = ({ children, tag = 'div', nl2br = true, ...rest }) =>
React.createElement(tag, {
dangerouslySetInnerHTML: {
__html: nl2br
? children && children.replace(/\n/g, '<br />')
: children,
},
...rest,
});
RawHTML.propTypes = {
children: PropTypes.string,
nl2br: PropTypes.bool,
tag: PropTypes.string,
};
Usage:
<RawHTML>{'First · Second'}</RawHTML>
<RawHTML tag="h2">{'First · Second'}</RawHTML>
<RawHTML tag="h2" className="test">{'First · Second'}</RawHTML>
<RawHTML>{'first line\nsecond line'}</RawHTML>
<RawHTML nl2br={false}>{'first line\nsecond line'}</RawHTML>
<RawHTML></RawHTML>
Output:
<div>First · Second</div>
<h2>First · Second</h2>
<h2 class="test">First · Second</h2>
<div>first line<br>second line</div>
<div>first line
second line</div>
<div></div>
It will break on:
<RawHTML><h1>First · Second</h1></RawHTML>
score:6
dangerouslySetInnerHTML
should not be used unless absolutely necessary. According to the docs, "This is mainly for cooperating with DOM string manipulation libraries". When you use it, you're giving up the benefit of React's DOM management.
In your case, it is pretty straightforward to convert to valid JSX syntax; just change class
attributes to className
. Or, as mentioned in the comments above, you can use the ReactBootstrap library which encapsulates Bootstrap elements into React components.
score:9
I used this library called Parser. It worked for what I needed.
import React, { Component } from 'react';
import Parser from 'html-react-parser';
class MyComponent extends Component {
render() {
<div>{Parser(this.state.message)}</div>
}
};
score:13
export class ModalBody extends Component{
rawMarkup(){
var rawMarkup = this.props.content
return { __html: rawMarkup };
}
render(){
return(
<div className="modal-body">
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
)
}
}
score:22
I have tried this pure component:
const RawHTML = ({children, className = ""}) =>
<div className={className}
dangerouslySetInnerHTML={{ __html: children.replace(/\n/g, '<br />')}} />
Features
- Takes
className
prop (easier to style it) - Replaces
\n
to<br />
(you often want to do that) - Place content as children when using the component like:
<RawHTML>{myHTML}</RawHTML>
I have placed the component in a Gist at Github: RawHTML: ReactJS pure component to render HTML
score:37
I have used this in quick and dirty situations:
// react render method:
render() {
return (
<div>
{ this.props.textOrHtml.indexOf('</') !== -1
? (
<div dangerouslySetInnerHTML={{__html: this.props.textOrHtml.replace(/(<? *script)/gi, 'illegalscript')}} >
</div>
)
: this.props.textOrHtml
}
</div>
)
}
score:66
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack.
It is better/safer to sanitise your raw HTML (using e.g., DOMPurify) before injecting it into the DOM via dangerouslySetInnerHTML
.
DOMPurify - a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. DOMPurify works with a secure default, but offers a lot of configurability and hooks.
Example:
import React from 'react'
import createDOMPurify from 'dompurify'
import { JSDOM } from 'jsdom'
const window = (new JSDOM('')).window
const DOMPurify = createDOMPurify(window)
const rawHTML = `
<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-expanded="true">
Dropdown
<span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1">
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Another action</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Something else here</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#">Separated link</a></li>
</ul>
</div>
`
const YourComponent = () => (
<div>
{ <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(rawHTML) }} /> }
</div>
)
export default YourComponent
score:229
There are now safer methods to render HTML. I covered this in a previous answer here. You have 4 options, the last uses dangerouslySetInnerHTML
.
Methods for rendering HTML
Easiest - Use Unicode, save the file as UTF-8 and set the
charset
to UTF-8.<div>{'First · Second'}</div>
Safer - Use the Unicode number for the entity inside a Javascript string.
<div>{'First \u00b7 Second'}</div>
or
<div>{'First ' + String.fromCharCode(183) + ' Second'}</div>
Or a mixed array with strings and JSX elements.
<div>{['First ', <span>·</span>, ' Second']}</div>
Last Resort - Insert raw HTML using
dangerouslySetInnerHTML
.<div dangerouslySetInnerHTML={{__html: 'First · Second'}} />
Source: stackoverflow.com
Related Query
- Rendering raw html with reactjs
- ReactJs - Converting raw HTML with nested React Component into JSX
- ReactJS errors with rendering basic html component via variable
- ReactJS component not rendering textarea with state variable
- add raw HTML with <script> inside Gatsby React page
- Initial static React HTML rendering with Webpack
- reactjs and rendering plain HTML
- Microservices UI Frontend with Java and ReactJS Server Side Rendering
- Add an external html file with query strings in reactjs
- Why ReactJS way of mixing code with HTML is a better design?
- Rendering custom html tag with react.js
- HTML rendering on server with Node.js
- Is node.js with reactjs as php template rendering service a good idea?
- HTML input autoFocus property not rendering with React.renderToStaticMarkup
- Why cannot render HTML with ReactJS
- React rendering variable with html characters escaped
- reactjs rendering with state or props
- weird html rendering issue with react
- Conditional Rendering in ReactJs for one part in Html
- Concatenating JSX fragments with HTML and then rendering the accumulated result
- Unit testing async rendering in ReactJS component with Jest
- Reactjs (Functional Component) Conditional Rendering with OR statement
- Why is ReactJS rendered HTML filled with empty spans?
- Selecting HTML dropdown with ReactJS in VBA
- Raw HTML passed with dangerouslySetInnerHTML React & Electron "lowercased"
- How to put value(data) into html attribute with ReactJS and ReactIntl
- map function loop when rendering with ReactJS and concat JSX syntax
- ReactJS not rendering HTML Audio correctly after first render
- How to load external libraries into jsdom for testing reactjs modules with enzyme full rendering
- How does render work in ReactJS with those HTML tags being "returned"
More Query from same tag
- Getting error parsing and displaying JSON object in ReactJS
- Sharing React component logic between separate renders
- how to use images in reactjs
- How to pass props while routing on click of Listitem of Material UI using v6
- How to generate custom url in React TypeScript with Class
- You cannot render a <Router> inside another <Router>. You should never have more than one in your app
- Should i use normal tag when i am using style component?
- Recognizing the user's text-align choise and controlling the text-align display, in a text-area (or text-field) in ReactJS
- How do I format a date in JSX?
- jQuery wrap equivalent in ReactJS
- Fetching data using API middleware taking an array of 3 action types, action.type is undefined in logger and state only updates once
- Find a match from one array to an objects property that is also an array
- ES-Lint Rule or Plugin to identify the commented code
- How can I get value from react modal bootstrap?
- How to render different Layouts using React?
- setState works only for first time in React js
- How to pass store state as a prop in react-redux-typescript?
- Test Coverage React, Istanbul -_registerComponent(...): Target container is not a DOM element
- Is there a way to combine Webpack modules to decrease file size?
- importing jQuery into React - TypeError for jQuery in componentDidMount
- How to add sorting to table with react virtualized?
- Apollo Client not sending headers to API endpoint
- ReactJS: post request with data through fetch
- Side Drawer Not Closing
- Unterminated JSX contents - react
- Eslint in React not correcting errors
- React.useRef([]) : Error React limits the number of renders to prevent an infinite loop
- When to use plain state over constructor(props)?
- How do I perform the mouse slider in react using react-router-dom?
- Custom props is undefined in React router-4