How do you render html content in react?


React's goal is in many ways to render HTML in a web page.

React renders HTML to the web page by using a function called ReactDOM.render().


The Render Function

The ReactDOM.render() function takes two arguments, HTML code and an HTML element.

The purpose of the function is to display the specified HTML code inside the specified HTML element.

But render where?

There is another folder in the root directory of your React project, named "public". In this folder, there is an index.html file.

You'll notice a single

in the body of this file. This is where our React application will be rendered.

Example

Display a paragraph inside an element with the id of "root":

ReactDOM.render(

Hello

, document.getElementById('root'));

The result is displayed in the

element:


  

Run Example »

Note that the element id does not have to be called "root", but this is the standard convention.



The HTML Code

The HTML code in this tutorial uses JSX which allows you to write HTML tags inside the JavaScript code:

Do not worry if the syntax is unfamiliar, you will learn more about JSX in the next chapter.

Example

Create a variable that contains HTML code and display it in the "root" node:

const myelement = (
  
Name
John
Elsa
); ReactDOM.render(myelement, document.getElementById('root'));

Run Example »


The Root Node

The root node is the HTML element where you want to display the result.

It is like a container for content managed by React.

It does NOT have to be a

element and it does NOT have to have the id='root':

Example

The root node can be called whatever you like:



  

Display the result in the

element:

ReactDOM.render(

Hallo

, document.getElementById('sandy'));

Run Example »



So is this the only way to render raw html with reactjs?

// http://facebook.github.io/react/docs/tutorial.html
// tutorial7.js
var converter = new Showdown.converter();
var Comment = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      

{this.props.author}

); } });

I know there are some cool ways to markup stuff with JSX, but I am mainly interested in being able to render raw html (with all the classes, inline styles, etc..). Something complicated like this:



I would not want to have to rewrite all of that in JSX.

Maybe I am thinking about this all wrong. Please correct me.

How do you render html content in react?

Al.G.

4,2276 gold badges34 silver badges55 bronze badges

asked Jan 14, 2015 at 1:01

4

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

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    {'First · Second'}

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    {'First \u00b7 Second'}

    or

    {'First ' + String.fromCharCode(183) + ' Second'}

  3. Or a mixed array with strings and JSX elements.

    {['First ', ·, ' Second']}

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

answered Jan 15, 2015 at 7:41

Brett DeWoodyBrett DeWoody

56.9k28 gold badges135 silver badges183 bronze badges

4

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 = `

`

const YourComponent = () => (
  
{
}
) export default YourComponent

answered May 31, 2019 at 11:22

YuciYuci

24.5k9 gold badges102 silver badges109 bronze badges

1

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.

answered Jun 21, 2015 at 0:02

How do you render html content in react?

Mike NiklesMike Nikles

1,39010 silver badges16 bronze badges

8

I have used this in quick and dirty situations:

// react render method:

render() {
    return (
      
{ this.props.textOrHtml.indexOf('
) : this.props.textOrHtml }
) }

How do you render html content in react?

Al.G.

4,2276 gold badges34 silver badges55 bronze badges

answered Jan 31, 2017 at 22:32

Cory RobinsonCory Robinson

4,2014 gold badges34 silver badges50 bronze badges

2

I have tried this pure component:

const RawHTML = ({children, className = ""}) => 
')}} />

Features

  • Takes classNameprop (easier to style it)
  • Replaces \n to
    (you often want to do that)
  • Place content as children when using the component like:
  • {myHTML}

I have placed the component in a Gist at Github: RawHTML: ReactJS pure component to render HTML

answered Aug 22, 2017 at 6:31

Netsi1964Netsi1964

2,9641 gold badge24 silver badges17 bronze badges

export class ModalBody extends Component{
    rawMarkup(){
        var rawMarkup = this.props.content
        return { __html: rawMarkup };
    }
    render(){
        return(
                
) } }

answered Mar 18, 2017 at 2:45

JozcarJozcar

9369 silver badges11 bronze badges

2

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() {
    
{Parser(this.state.message)}
} };

answered Oct 24, 2018 at 1:42

How do you render html content in react?

ecairolecairol

5,9141 gold badge26 silver badges23 bronze badges

2

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.

How do you render html content in react?

Bondolin

2,6357 gold badges31 silver badges59 bronze badges

answered Jan 14, 2015 at 12:58

How do you render html content in react?

3

Here's a little less opinionated version of the RawHTML function posted before. It lets you:

  • configure the tag
  • optionally replace newlines to
    's
  • pass extra props that RawHTML will pass to the created element
  • supply an empty string (RawHTML>)

Here's the component:

const RawHTML = ({ children, tag = 'div', nl2br = true, ...rest }) =>
    React.createElement(tag, {
        dangerouslySetInnerHTML: {
            __html: nl2br
                ? children && children.replace(/\n/g, '
') : children, }, ...rest, }); RawHTML.propTypes = { children: PropTypes.string, nl2br: PropTypes.bool, tag: PropTypes.string, };

Usage:

{'First · Second'}
{'First · Second'}
{'First · Second'}
{'first line\nsecond line'}
{'first line\nsecond line'}

Output:

First · Second

First · Second

First · Second

first line
second line
first line second line

It will break on:

First · Second

answered Jul 11, 2018 at 11:58

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: