Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a string as React component

Tags:

reactjs

I want to render the react components with a string as the input which i am receiving dynamically from another page. BUt i will have the references for the react components. Here is the example

Page1:
-----------------------------
loadPage('<div><Header value=signin></Header></div>');

Page2:
--------------------------------
var React =require('react');
var Header = require('./header');

var home = React.createClass({

loadPage:function(str){ 

           this.setState({
             content : str 
           });

  },

 render : function(){

  return {this.state.content}
 }

});

In this example i am receiving Header component as string , and i have the reference of Header component in my receiving page . How can i substitute the string with the actual react component

like image 465
jazean Avatar asked Apr 07 '16 09:04

jazean


People also ask

How do I render a string in React?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

Can React components return string?

React component can return only string, it's perfectly valid (and works as OP stated) ... but this use case is not supported. Using components to just return a string is not a good choice. It can be ineffective when you need many translated strings in one component.

How do I render HTML code 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() .


2 Answers

This react-jsx-parser component looks like it will solve your problem

like image 191
Jonathan Wickens Avatar answered Oct 19 '22 21:10

Jonathan Wickens


To render a react component using a string you can use.

var MyComponent = Components[type + "Component"];
return <MyComponent />;

For more information check the response here : React / JSX Dynamic Component Name

like image 38
Aaleks Avatar answered Oct 19 '22 22:10

Aaleks