Escape HTML in React using HTML-Entities
The html-entities
package
The html-entities NPM package allows HTML character decoding for things like ampersands (&) in react.
Once installed (npm install html-entities
), characters can be decoded as follows in a React Component definition. In this example, we have a varaible, name
which is being decoded if it is present.
import {decode} from "html-entities";
...
return (
...
<div>{name ? decode(`${name}`) : ''}</div>
...
);
The he
package
An alternative to html-entities is the he library.
After installing (npm install he
), the usage would be:
import he from "he";
... he.decode(`${name}`) ...
Revisions
- Mar 19, 2025
- Wrapped html-entities in double quotes in the import statement per TypeScript practices.
- Added the he library as an alternative to html-entities.
Feedback?
Email us at enquiries@kinsa.cc.