1

In ReactJS I am trying to render a component from a string that I dynamically create. My render function looks like this:

render() {
 var content = '<h1>Hello</h1>'
 content += "<Link href={'http://www.google.com'} text={'Click Here'} />
 content += '<h1>World</h1>';
return (
   <div>
     <div dangerouslySetInnerHTML={content} />
   </div>
);
}

Except the component link is not being render and it is being printed as html. What am I doing wrong?

7
  • Are you using react-router or a custom Link component? Commented Aug 11, 2017 at 17:31
  • 1
    Link doesn't exist in HTML. You are telling React to treat interpret the string as HTML and that's exactly what it does. Commented Aug 11, 2017 at 17:31
  • Link is an easy example. My real code uses a custom compontent Commented Aug 11, 2017 at 17:32
  • 3
    Then you cannot tell React to treat your string as HTML. You are getting what you are asking for. JSX !== HTML. Putting JSX inside a string is the wrong approach from the start. You are saying you are creating it dynamically. How/where/why? We should find a better solution than that. Commented Aug 11, 2017 at 17:32
  • I think you may be misusing components a bit. What you can do is pass in a data object and then have a type prop and based on the type prop the container component will render a different child component. I am unsure as to what the exact implementation is, so if you could elaborate on that that would help, but it sounds like you are taking an adverse approach to using components. I can guarantee there is a way to do this that is idiomatic in react. Commented Aug 11, 2017 at 17:35

0

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.