user3379926
user3379926

Reputation: 3945

React + Backbone, Target container is not a DOM element

Note: This is a react error being thrown.

So I am trying an experiment where I render a post component from a backbone router based on that page. Now I know you would not typically do things this way, things can get messy and such. But again It's just an experiment.

So I have the following route in backbone (Note the react call):

AisisWriter.Routers.Posts = Backbone.Router.extend({

  writer_posts: null,

  posts: null,

  mountNode: $('#blog-manage'),

  routes : {
      '': 'index'
  },

  initialize: function() {
    this.writer_posts = new AisisWriter.Collections.Posts();
  },

  index: function() {
    var options = { reset: true };
    this.writer_posts.fetch(options).then(this.postsRecieved, this.serverError);
  },

  // Deal with the posts received
  postsRecieved: function(collection, response, options) {
    this.posts = collection;

    // Walk through the posts.
    $.each(this.posts, function(key, value){
      // value is an array of objects.
      $.each(value, function(index, post_object){
        React.renderComponent(new Post({post: post_object}), this.mountNode);
      });
    });
  },

  // Deal with any server errors
  serverError: function() {
    console.log('There was an error trying to fetch the posts.');
  }

});

The idea is that it should spit out a post title on to the page, one right after the other (I have a feeling it will only do it once).

But the issue is that the console is saying:

Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

Is this because of how I am trying to render the component?

Upvotes: 4

Views: 7441

Answers (2)

Sophie Alpert
Sophie Alpert

Reputation: 143134

You're setting this.mountNode to $('#blog-manage'), which is a jQuery object (essentially an array of nodes). If you instead do

mountNode: $('#blog-manage')[0]

or

mountNode: $('#blog-manage').get(0)

then you'll have reference to the actual DOM node.

Upvotes: 10

Ross Allen
Ross Allen

Reputation: 44880

React.renderComponent renders a component into a real DOM element. The exception is being thrown because you aren't passing a DOM element as the required second argument.

ReactComponent renderComponent(
  ReactComponent component,
  DOMElement container,
  [function callback]
)

Render a React component into the DOM in the supplied container and return a reference to the component.

If you just want the HTML from React, you can use React.renderComponentToStaticMarkup instead.

Upvotes: 3

Related Questions