1

I am trying to load a component dynamically from html string. for example: I am having a html string like following which is from json.

 <div>This is some html content having a component of <Combobox params="option1,option2,option3"/></div>

here <Combobox params="option1,option2,option3"/> is a React component which i need to render as a HTML combobox with options 1,2 and 3 along with the texts. So, is there any way to do this kind of things in React.

2 Answers 2

2

The entire JSX can be parsed to HTML using renderToString method.

import ReactDOMServer from 'react-dom/server';   

render() {
  const html = ReactDOMServer.renderToString(<div><Combobox /></div>);
  return (
    <div dangerouslySetInnerHTML={html}></div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

hai vijay above code shows me error beacuse in my json it is a html string with react component name. but here we need to pass it like a raw
2

To build on vijayst's answer, if you're using redux/react-redux, and this happens to be a "connected" component, you'll need to import and pass the store along again.

import ReactDOMServer from 'react-dom/server';
import { Provider } from 'react-redux';
import store from '../redux/store';

render() {
  const html = ReactDOMServer.renderToString(<Provider store={store}><Combobox /></Provider>);
  return <div dangerouslySetInnerHTML={html}></div>;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.