12

I want to add a react component, a comments feature, to a non-react site.

The site has a news page with infinite scrolling. Under each news story I want to include the react comments component. I plan to model it after the FB tutorial here: http://facebook.github.io/react/docs/tutorial.html

My question is, how do I dynamically mount each React component to a DOM story element? Basically, I want to have many instances of the same react comments component, but with each instance tied to a unique story (div).

I think I need to render the react component on the server side, where I can dynamically set the React.renderComponent. Any pointers/examples appreciated.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
  • @jason_gelinas did you ever get this working? I've seen there are naming conflicts with multiple instances on one page, but your use case is a great one for SEO. – YPCrumble May 14 '15 at 16:50

1 Answers1

11

When the post is added you need to have your data and the target dom node (we'll call these variables data and el)

React.render(<MyComponent data={data} />, el);

Or without JSX

React.render(React.createElement(MyComponent, {data: data}), el);

To clean up:

React.unmountComponentAtNode(el);

For server side rendering you can do:

React.renderToString(React.createElement(MyComponent, {data: data}))

and as long as the result of that ends up as el on the client, you can mount it with React.render as mentioned above.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • 5
    is it OK to mount React elements like you suggest multiple times in the same DOM? I think that is what the question specifically asks: "I want to have many instances of the same react comments component, but with each instance tied to a unique story (div)" – YPCrumble Jul 08 '15 at 20:29
  • 8
    Yeah, you can have hundreds of roots. – Brigand Jul 08 '15 at 22:27