kevinzf
kevinzf

Reputation: 193

React render HTML from parent component

I run into an issue in the rendering. I did some search online, but I didn't find a solution.

In the parent component:

<Child prop1={this.getHeader()}>

getHeader() : function () {
  return (<div> Header </div>)
}

In the Child component:

render() : function () {
  return (<div> {this.props.prop1} </div>)
}

However, the div didn't get rendered. I checked other solution and tried dangerouslySetInnerHTML, but it will render the string of " Header " rather than the element. Could i get some help?

Upvotes: 1

Views: 877

Answers (1)

Maxim Mazurok
Maxim Mazurok

Reputation: 4138

Here's a working solution:

class Parent extends React.Component {
  getHeader() {
    return <div> Header </div>;
  }

  render() {
    return <Child prop1={this.getHeader()} />;
  }
}

class Child extends React.Component {
  render() {
    return <div> {this.props.prop1} </div>;
  }
}

ReactDOM.render(<Parent />, document.querySelector('#app'));

https://jsfiddle.net/u5m29cw1/6/

Upvotes: 2

Related Questions