Rendering a string as React component

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

5

5 Answers

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

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

2

If you can live with having all your components in one module, then this works pretty well:

 import * as widgets from 'widgets'; var Type = widgets[this.props.componentId]; ... <Type />

The wildcard import works like a cut-rate component registry.

Built in way

Without any package You can use the built in react attribute dangerouslySetInnerHTML to pass your string, and it will render it as an HTML

function Component() { const stringElement = "<h1> My Title </h1>"; return ( <div dangerouslySetInnerHTML={{ __html: stringElement }}> </div> );
}

And it would work fine

2

one more way to use component

const a = { b: { icon: <component props /> }
}

In render function

 return( {a.b.icon} )

This will render your component in your JSON object

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like