react render doesn't show anything

12.6k Views Asked by At

My react codepen is not showing anything.

JS

class HelloWorld extends React.Component {
    render() {
        return (<div>Hello World!</div>);
    }
}
var app = document.getElementById("mainapp");
React.render(<HelloWorld />, app);

HTML

<div id='mainapp'></div>

I imported React and ReactDOM trough a cdn. And if I type React/ReactDOM in the console it is imported correctly. This code doesn't show any errors yet I see nothing. I tested this on multiple browsers (chrome, firefox, icecat) but still no results... I'm using bable is a preprocessor.

3

There are 3 best solutions below

0
On BEST ANSWER

ReactDOM.render not React.render.

class HelloWorld extends React.Component {
    render() {
        return <div>Hello World!</div>;
    }
}
var app = document.getElementById("mainapp");
ReactDOM.render(
  <HelloWorld/>,
  app
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id='mainapp'></div>

1
On

Your component needs to return an element instead of a naked string. Try to modify it to <div>Hello World!</div>

0
On

Two things

  1. You need to return a valid react element
  2. Use ReactDOM.render instead of React.render

Snippet

class HelloWorld extends React.Component {
    render() {
        return <div>"Hello World!"</div>
    }
}
var app = document.getElementById("mainapp");
ReactDOM.render(<HelloWorld />, app);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
<div id="mainapp"></div>

Also see this answer on why you should use ReactDOM

react vs react DOM confusion