Monday, December 3, 2018

Working with react dangerouslySetInnerHTML attribute

This tutorial explains how to use react dangerouslySetInnerHTML attribute inside react application component. 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. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.

NOTE :Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.
Working with react dangerouslySetInnerHTML attribute.


Lets see the below examples for dangerouslySetInnerHTML attribute.

Example -1 : 

In this example, we are simply displaying text using dangerouslySetInnerHTML attribute.

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

// inner HTML Example...
function createMarkup() {
  return {
    __html: "<h1>This is example for dangerouslySetInnerHTML attribute.</h1>"
  };
}

//React component...
function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

Output :
----------------------

Example -2 : 

In this example, we are simply displaying text and link using dangerouslySetInnerHTML attribute.
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

// covert urls to clickable link
function textToLink(text) {
  var finalText = text
    .replace(/&/g, "&")
    .replace(/</g, "<")
    .replace(/>/g, ">")
    .replace(/"/g, """);
  var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
  var htmlData = finalText.replace(
    urlPattern,
    '<a target="_blank" href="$&">$&</a>'
  );
  return htmlData;
}

// inner HTML Example...
function createMarkup() {
  let getValue = textToLink(
    "display text with link :- https://www.skptricks.com/2018/12/javascript-timers-with-examples.html"
  );
  return {
    __html: getValue
  };
}

//React component...
function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

const rootElement = document.getElementById("root");
ReactDOM.render(<MyComponent />, rootElement);

Output :
----------------------
Check out this link :  https://codesandbox.io/s/42q8krj1ow

This is all about react dangerouslySetInnerHTML attribute. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment