ReactJs 0.12 Target container is not a DOM element

I am very confused as to why I am getting this error in the console. I have read all the boards and as far as I know I am doing it right.

On my page I have

<div id="aisis-writer"></div>

      

where I want to bind a react element. Then I created a simple React component that does nothing:

var AisisWriter = React.createClass({
  getInitialState: function(){},

  componentDidMount: function(){},

  render: function(){
    return null;
  }
});

React.render(
  <AisisWriter />,
  document.getElementById('aisis-writer')
);

      

Very simple. When I load the page I see: Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element.

So, I think ok, maybe I messed something up, so in the console I do:

document.getElementById('aisis-writer');

      

And I will return:

<div id="aisis-writer"></div>

      

So am I missing something entirely? Why am I getting this error?

+3


source to share


2 answers


I have the same problem and this is because the scripts are executed before the DOM has parsed (perhaps you include your scripts in the index head). To fix this, you can use a defer

script in your include.

<head>
    ...
    <script src="app.js" defer></script>
    ...
</head>

      

The defer attribute loads your script when the page has finished parsing, so even if you put your scripts in your index head, you make sure the script finds all your elements because they'll be there.

W3Schools defer



Update

The standard way is to add your scripts to the end of the body. They should be loaded after the DOM has been created, so the error should go away because when you get to the DOM with your JavaScript, it already exists. defer

widespread among browsers, so you shouldn't have a problem unless you're working with really old ones. You can use defer

to order your code. It seems more intuitive to have your "dependencies" inside the header and your "code" inside the body.

Here you have a link where to use defer .

+5


source


The following piece of code tries to find an element with an id aisis-writer

where it says document.getElementById('aisis-writer')

but cannot find it on the page.

React.render(
  <AisisWriter />,
  document.getElementById('aisis-writer')
);

      

This can happen because



  • JavaScript is executed before the line <div id="aisis-writer"></div>

  • Or you may have a wrong ID

Decision:

  • You can place operators React.render

    inwindow.onload

  • Or make sure React.render

    only appears after <div id="aisis-writer"></div>

    on the page
+1


source







All Articles