<script>
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
</script>
<div id="root">
</div>
I am running the html snippet but getting a console error message , this code is from https://reactjs.org/docs/hello-world.html ,it runs fine on codepen but not my local browser, please help as i am new to react.js
CodePudding user response:
That snippet won't run in your browser's console as-is. In the code pen go to settings > JS > Add External Scripts/Pens. You'll see react and react-dom are dependencies for the code to run.
This tutorial for create-react-app will help you get everything installed correctly so you can try the hello world example - https://create-react-app.dev/docs/getting-started/
CodePudding user response:
Here's the full setup in order for this example code to run:
<!-- INCLUDE REACT LIB -->
<script src="https://unpkg.com/react@18/umd/react.production.min.js" crossorigin></script>
<!-- INCLUDE REACTDOM LIB -->
<script src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js" crossorigin></script>
<!-- INCLUDE BABEL COMPILER LIB FOR JSX -->
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>
<!-- Change the type to text/babel in order for the Babel compiler to detect and compile the JSX syntax -->
<script type="text/babel">
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
</script>
You can find the CDN links used in this example for the React, ReactDOM and Babel libraries on the link that @abo mentioned above.
Happy Hacking and welcome to the wonderful world of React! ;)