Run simple react js in browser locally
First of all your html file has some wrong syntax. head
tag is used for non visual elements. You need to add that h1
tag inside a body
tag. If your knowledge on html is not that good I suggest you to get a little familiar with HTML and Javascript before diving into React.
Second problem is that you are missing required react scripts in your html. You need to add react and required javascript libraries to your file before using react. You can find more information about that here
The third problem I can see is that you are missing a tag with id root
in your html. Line with document.getElementById('root')
trying to find an element with the id root in your html to render react element inside.
I suggest you to check W3Schools for quick and easy way to learn basic HTML and Javascript if you are not familiar with. After that you can start learning React with official tool create-react-app. This will help you to understand project structure and how things work better.
You can run react.js directly into your browser NPM or NODE.JS are NOT REQUIRED. Here is a snippet:
// main.js
/* You don't need these imports
** import React from 'react';
** import ReactDOM from 'react-dom';
*/
// React and ReactDOM are already imported in you HTML
// Also import / require are NodeJS thing that doesn't exist in a browser
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('the_root_of_your_reactJS_component')
);
}
setInterval(tick, 1000);
<!-- index.html -->
<body>
<!-- some HTML -->
<div id="the_root_of_your_reactJS_component"></div>
<!-- some other HTML -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<!-- babel is required in order to parse JSX -->
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<!-- import react.js -->
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"> </script>
<!-- import react-dom.js -->
<script type="text/babel" src="main.js"></script>
<!-- import your JS and add - type="text/babel" - otherwise babel wont parse it -->
</body>
At the very least, you will need to load React (and ReactDOM) in clock.html
. Some instructions are available in the React installation docs.
If you want to get started quick, an easier option might be to use create-react-app. You just need to install node + npm and then run the few commands listed in the create-react-app README:
npm install -g create-react-app
create-react-app my-app
cd my-app/
npm start
That will create a simple "Hello, world" app and open it in your browser. Then you can make changes to it and see it update in the browser in real time.