1

I'm trying to just send the client a single line like so:

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

which is valid HTML5.

I then want to build the page back up with React.js. E.g. (note modified code, I had some errors in my simplified code),

React = require('react');
e = React.createElement;
App = React.createClass({
  render: function(){
    return e('html', null, 
            (e('head', null, 
              e('script', {src: '/js/app.js'})), 
            e('body', null, 'hello!')));
  }
});
React.render(e(App, null), document.documentElement);

the resulting DOM:

<html>
<head></head>
<body data-reactid=".0.0">hello!</body>
<body></body>
</html>

1 Answer 1

2

You don't need to build <html>, <head> and <body> tags in React. Browser renders them anyway if they are missing in received HTML document.

All you need to do is:

var React = require('react');

var App = React.createClass({displayName: "App",
  render: function(){
    return (
        React.createElement("h1", null, "Hello, World")
    );
  }
});

document.addEventListener("DOMContentLoaded", function(event) {
    React.render(React.createElement(App, null), document.body);
});

Also, instead of tricks like e = React.createElement try using jsx which makes code much more readable:

var React = require('react');

var App = React.createClass({
  render: function(){
    return (
        <h1>Hello, World</h1>
    );
  }
});

document.addEventListener("DOMContentLoaded", function(event) {
    React.render(<App />, document.body);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Since I'm just sending <script src="/js/app.js"></script> if I render to document.body it will error out on me since the browser hasn't created the body tag yet. Also, I will want to add css references to the head tag. I'm not using JSX because I'm writing in LiveScript, I just converted it to JavaScript to make it easier for others to comment on.
Also, I'm coming from using Mithril.js, so although I'm finding similarities, there's enough differences that I'm having a hard time figure this out.
That's why I've added DOMContentLoaded event listener to make sure that document.body is ready. What kind of error do you have in your case?
Sorry, I didn't notice that. I'll try it out.
OK, that works, I guess I can put the CSS files in the body, not as clean as I would like to do it but it works.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.