score:85
If XSS is your primary concern, you can use DOMPurify
to sanitize your HTML before inserting it in the DOM via dangerouslySetInnerHTML
. It's just 10K minified. And it works in Node too.
score:0
I'm faced the same issue and ended with better solution. if your input something like below and solution will work for you using lodash
<em>paragraph text example:</em>
My Solution:
import _ from 'lodash';
const createMarkup = encodedHtml => ({
__html: _.unescape(encodedHtml),
});
/* eslint-disable react/no-danger */
const Notes = ({ label }) => (
<div>
<div dangerouslySetInnerHTML={createMarkup(label)} />
</div>
);
score:0
Safe alternative to dangerouslySetInnerHTML
I'm curious if there's a performant, safe way to dynamically load blog pages within my app
It's interesting that, while the question is for an alternative to dangerouselySetInnerHTML
, all of the answer instruct to use it anyway. Does this mean you're stuck with no alternative? No, just no easy one.
Alternative 1: Rewrite your app to pass data to components instead
Initially, I was going to store the posts in raw HTML
It doesn't seem from the answer like this is a requirement. It might be implemented as an easy solution, to not worry about the data schema matching your components. But it's unlikely this is a hard requirement.
It should be possible to re-architect your app to not rely on storing raw HTML, though it might mean a lot of work, depending on the app.
Alternative 2: Don't write your own page builder
If you're just interested in having a blog on your site, it's maybe not worth it to write your own page builder. Even if you want tight integration with other parts of your site, that's still possible if you use something like WordPress.
Alternative 3 (WordPress only): Use InnerBlocks
If you're currently using dangerouselySetInnerHTML
in a WordPress block, you can convert it to use InnerBlocks
instead.
score:1
Use React library Interweave.
- Safely render HTML without using dangerouslySetInnerHTML.
- Safely strip HTML tags.
- Automatic XSS and injection protection.
- Clean HTML attributes using filters.
- Interpolate components using matchers.
- Autolink URLs, IPs, emails, and hashtags.
- Render Emoji and emoticon characters.
score:4
If you're sure the input HTML is safe (without XSS risk) but might be malformed (e.g. have a random <
in text), and you want to prevent your app from failing because of unexpected DOM change, then you could try this:
function sanitize(html) {
var doc = document.createElement('div');
doc.innerHTML = html;
return doc.innerHTML;
}
(Based on https://stackoverflow.com/a/14216406/115493)
But if you have the slightest doubt that your HTML might be not-XSS-safe, use DOMPurify as mentioned above.
score:4
As stated in other answers, a lot of libraries (dompurify, xss, etc) can parse the HTML you are giving to the browser, remove any malicious part and display it safely.
The issue is: how do you enforce these libraries are used.
To do so, you can install RisXSS which is an ESLint plugin that will warn the uses of dangerouslySetInnerHTML
if you do not sanitize it before (in a sense, this is an improved version of react/no-danger
ESLint rule).
To do so, install dompurify
and eslint-plugin-risxss
:
npm install dompurify eslint-plugin-risxss
Add risxss
to your ESLint plugins then use DOMPurify:
import { sanitize } from 'dompurify';
export const MyArticle = ({ post }) => (
<>
<div dangerouslySetInnerHTML={{ post.content }} /> {/* You will receive a warning */}
<div dangerouslySetInnerHTML={{ __html: sanitize(post.content) }} /> {/* All good here */}
</>
);
Disclaimer: I am a contributor of RisXSS plugin.
score:10
https://facebook.github.io/react/tips/dangerously-set-inner-html.html
"The prop name dangerouslySetInnerHTML is intentionally chosen to be frightening. ..."
"After fully understanding the security ramifications and properly sanitizing the data..."
I figure, if you trust your own CMS/Server (and not receiving from a 3rd party), which has sanitized the data (this step is also done), then you can insert using dangerouslySetInnerHTML
.
As Morhaus said, maybe use DOMPurify as it (bonus) probably handles this unfortunate bit: "so the HTML provided must be well-formed (ie., pass XML validation)." I suspect some content using the non-XML version of HTML5 might otherwise be an issue. (Note: I haven't used it myself yet, since i'm new like you.)
score:26
The article How to prevent XSS attacks when using dangerouslySetInnerHTML in React suggests to use jam3/no-sanitizer-with-danger eslint rule to check that the content passed to dangerouslySetInnerHTML is wrapped in this sanitizer function
Example of valid code is
const sanitizer = dompurify.sanitize;
return <div dangerouslySetInnerHTML={{__html: sanitizer(title)}} />; // Good
It also describes 3 sanitizer libraries:
DOMPurify
Xss.
xss-filters.
Source: stackoverflow.com
Related Query
- Safe alternative to dangerouslySetInnerHTML
- React.js: Set innerHTML vs dangerouslySetInnerHTML
- Is it safe to store a JWT in localStorage with ReactJS?
- Is there a synchronous alternative of setState() in Reactjs
- Is it safe to use ref.current as useEffect's dependency when ref points to a DOM element?
- React: Script tag not working when inserted using dangerouslySetInnerHTML
- React - componentWillReceiveProps alternative
- Making an HTML string from a React component in background, how to use the string by dangerouslySetInnerHTML in another React component
- Redux Alternative
- Is it safe to use ReactDOM.createPortal() with document.body?
- How to add onclick event to a string rendered by dangerouslysetInnerHtml in reactjs?
- Is dangerouslySetInnerHTML the only way to render HTML from an API in React?
- What is the alternative of makeStyles for Material UI v.5
- Object.entries() alternative for Internet Explorer and ReactJS
- dangerouslySetInnerHtml doesn't update during render
- Are there alternative libraries for Relay and GraphQL?
- FP alternative to polymorphism in JavaScript/ReactJS
- Is it safe to useMemo for JSX?
- React: using React component inside of dangerouslySetInnerHTML
- Is it safe to call react hooks based on a constant condition?
- What's the best alternative to update nested React state property with setState()?
- Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps
- Is it safe to use a useState "setter" function as a callback ref?
- What is the alternative for Redirect in react-router-dom v 6.0.0?
- Is it safe to render a react portal into another component DOM?
- Render SVGSVGElement in React JS without dangerouslySetInnerHtml
- Using Fragment to insert HTML rendered on the back end via dangerouslySetInnerHTML
- How to use dangerouslySetInnerHTML without the wrapper div?
- What's the alternative to use hooks inside non React component?
- What is happening such I receive dangerouslySetInnerHTML warning and empty content using Next.js?
More Query from same tag
- How can I edit the value of the timepicker from the keyboard?
- Firebase App named '[DEFAULT]' already exists REACT
- How to push data coming from setInterval into an array
- React sending empty form values to backend
- Typing props spread when using InferProps<> from prop-types
- Spotify API error 400: "only valid bearer authentication supported"
- No matching version found for gulp-sourcemaps@1.7.0
- Nested Array in Redux Resetting Value in React
- How do I retrieve the child of the child of the child's data from my firebase Realtime database?
- What are the difference/similarities between React (app framework from Facebook) and react.js (reactive extensions for JS)?
- Passing a value from child to parent react
- PDF displaying in laravel
- How do I define the security rules where only logged in user can read and write all of the collections and subcollection?
- material-ui-popup-state change button color
- Creating 'Div' and 'Span' Components in React Native
- What is an in-memory API?
- Intersection Observer with React JS
- i cant use the map function TypeError: Cannot read property 'map' of undefined
- useCollectionData returns undefined in react-firebase-hooks
- Button shifts location when changing content of react component
- react-virtualized Data Table Example
- React: How to use setState inside functional component?
- Error Handle and Log the errors in React js
- How does event handler on ref in react persist between renders?
- DatepickerInput defaultValue is not working
- How to call Parent containers function from child component in Reactjs
- Can't use props for styled components with emotion-js and typescript
- useContext is not displaying the updated state (when data is retrieved from firebase in useEffect hook in global file) in child component
- I got an error for using React.useRef inside a react function component
- React JSX code not compiling