0

I have a react component where one of the properties passed is a string. However this string is an html component, such as,

            <Example time="4 <sup> th </sup>  September">
                Text
            </Example>

However on my received component I want this to be rendered as html instead of a string.

<h6 className="..."> {time} </h6>

Joe
  • 21
  • 3
  • Could you provide more context to this? What is the property look like? – Ryan Le Sep 04 '21 at 07:06
  • I think I might have an answer for this, but need to make sure it matches your needs. – Ryan Le Sep 04 '21 at 07:07
  • Can you try to provide us a bit more context for what you are trying to accomplish. https://stackoverflow.com/help/minimal-reproducible-example Are you just wanting to render the `time` prop into a header element? – Drew Reese Sep 04 '21 at 07:09
  • @RyanLe I thought I did, the example provided above it like what I am trying to achieve. I have a react component which takes a date, as a string, however I want to utilize the tag in my date. So I am trying to figure out how I can pass a string and render it essentially as an html tag. – Joe Sep 04 '21 at 07:13
  • Does your `` come from some property? Try to provide more context to your question.. Like where are your properties came from, and how the whole component looks like. – Ryan Le Sep 04 '21 at 07:17
  • is not something I made it is a html tag. – Joe Sep 04 '21 at 07:24
  • Does this answer your question? [react use dangerouslySetInnerHTML to render json with html tags](https://stackoverflow.com/questions/43795680/react-use-dangerouslysetinnerhtml-to-render-json-with-html-tags) – Noam Yizraeli Sep 26 '21 at 15:34

2 Answers2

1
dangerouslySetInnerHTML 

from docs

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

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

here is docs link

Damian Busz
  • 1,693
  • 1
  • 10
  • 22
0

Basicaly you want to show html given from another source (usually as text) dangerouslySetInnerHTML is under the DOM elements in react as an attribute and is React's replacement for innerHTML known from vanilla JavaScript

when using dangerouslySetInnerHTML attribute you need to send an object with an __html key like so:

<div dangerouslySetInnerHTML={{ __html: 'beware of dangerously Set InnerHTML' }}>

watch out of this attribute, its not called this way for no reason, unvigilent usage can open you up for cross-site scripting attack (XSS attack)

further explanation thanks to @FrancisJohn in this thread:

the scenes when you use dangerouslySetInnerHTML it lets React know that the HTML inside of that component is not something it cares about.

Because React uses a virtual DOM, when it goes to compare the diff against the actual DOM, it can straight up bypass checking the children of that node because it knows the HTML is coming from another source. So there's performance gains.

Noam Yizraeli
  • 4,446
  • 18
  • 35