6

In Backbone.js, you can specify a view's element by using the el property or by calling view.setElement().

Is there an equivalent way of hooking up a React.js component to an existing DOM element?

cantera
  • 24,479
  • 25
  • 95
  • 138
  • Perhaps this will help... http://stackoverflow.com/questions/27160763/can-a-react-component-manipulate-an-existing-dom-node/34630247#34630247 – gdoumenc Jan 06 '16 at 10:01

1 Answers1

10

I'm not overly familiar with Backbone, but to hook a React component into the DOM you use the renderComponent function. The first arg is the component, and the second is a DOM element:

React.renderComponent(<SampleComponent />, document.getElementById('app'));

Updated per the context given in the comments:

React hooks up to an element by replacing its contents, but not the element itself. You can call renderComponent() more than once on that element and it will run the same diff algorithm each time. This is handy if you want to pass in different props, pre-render on the server, or render a different component entirely. The same process is used to update the actual DOM each time, just like if you were to use setState() within the component itself.

Michael LaCroix
  • 5,780
  • 1
  • 24
  • 13
  • Doesn't that place the SampleComponent as a child of #app? I think the OP's looking to replace an existing element with the component. – Edward M Smith Feb 08 '14 at 13:29
  • @EdwardMSmith Ah, I wasn't acquainted with Backbone's behavior. I'll update my answer. – Michael LaCroix Feb 08 '14 at 23:03
  • 1
    Thank you - yes to clarify, I'm referring to elements loaded server-side like a select menu option that needs to know whether its default sort order is ascending or descending. So the element already exists when the page loads and I need to use Backbone/React to bind additional behavior/data to it without having to render it from scratch with a client-side template or React component. I can expand my question if it's more helpful. – cantera Feb 08 '14 at 23:17
  • @cantera React controls the rendering (it needs to in order to effectively diff against its virtual DOM), so we're going to need to re-render it anyway. Unless you are pre-rendering on the server with `renderComponentToString()`, in which case it will run the diff and not change anything. Do you have a jsfiddle or some other example with more scope? I'd be happy to help. – Michael LaCroix Feb 08 '14 at 23:49
  • 2
    In [React version 0.12](http://facebook.github.io/react/blog/2014/10/28/react-v0.12.html#new-terminology-amp-updated-apis) `React.renderComponent` has been changed to `React.render` – Matti John Jan 11 '15 at 22:51