Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React dangerouslySetInnerHTML printing out '[object Object]'

I have my element:

dangerouslySetInnerHTML: { __html: this.props.html.map(React.renderToStaticMarkup).join('') }

this.props.html is an array of React Elements (built up from this method):

makeOutput(model) {
    return <Key model={model} />;
}

When I run my code above in a breakpoint, I do get:

> this.props.html.map(React.renderToStaticMarkup).join('')
> "<span>b</span>"

However, when the element is output to the DOM, all that's shown is [object Object]. Any reason for this?

like image 693
benhowdle89 Avatar asked Jun 18 '15 00:06

benhowdle89


2 Answers

This example shows that the technique works with no problem:

function makeOutput(text) {
  return <Wrapper text={text} />;
}

var Wrapper = React.createClass({
  render() {
    return <div>Wrapping: {this.props.text}</div>
  }
});

var App = React.createClass({
  render() {
    var items = [
      makeOutput("one"),
      makeOutput("two"),
      makeOutput("three")
    ];
    return (
      <div dangerouslySetInnerHTML={{__html: items.map(React.renderToStaticMarkup).join("") }} />
    );
  }
});

React.render(<App />, document.getElementById("container"));

The problem must lie in some code you haven't yet revealed.

like image 160
Michelle Tilley Avatar answered Nov 13 '22 11:11

Michelle Tilley


Try by convert your HTML to string type

// before
const content = <p>Hello</p>

// after update
const content = `<p>Hello</p>`

// implementation
<div dangerouslySetInnerHTML={{ __html: content }} />
like image 1
Irwan Avatar answered Nov 13 '22 11:11

Irwan