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
30.1k21 gold badges119 silver badges129 bronze badges
asked Nov 24, 2014 at 19:05
1
  • @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. Commented May 14, 2015 at 16:50

1 Answer 1

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.

answered Nov 24, 2014 at 20:43

2 Comments

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)"
Yeah, you can have hundreds of roots.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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