earthyearth earthyearth - 3 years ago 168
React JSX Question

How to use render () in react?

I just started learning React and trying to get Render() to work.

I couldn't get the content to be added to my html page.

This is my index.html

<html>
<head>
<script async src="/bundle.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>


and this is my main.js

import React from 'react';
import ReactDOM from 'react-dom';

class Layout extends React.Component{
render(){
return (
<h1>It works!</h1>
);
}
}

document.addEventListener('DOMContentLoaded', function() {
ReactDOM.render(<Layout />, document.getElementById('app'));
});


I have tried not using a js referenced code, but both do not work.

<html>
<head>
<script src="bundle.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
ReactDOM.render(<h1>Hello World</h1>, document.getElementById('app'));
</script>
</body>
</html>

Answer Source

To render the dom you just need to put the script tag after the element you want to render on.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React app</title>
</head>
<body>
<div id="app"></div>
<script src="app.min.js"></script>
</body>
</html>

In main.js:

ReactDOM.render(<App />, document.getElementById('app'))

No need to put a event listener that way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download