Simple React Library Example

Table of Contents

React can be used on your website by just adding some JS files from a CDN without having to setup a local Node.js instance.

Files

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>First Component</title>
</head>
<body>
  <div id="root"></div>

  <script src="https://unpkg.com/react/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>

  <script src="https://unpkg.com/babel-standalone"></script>
  <script src="index.js" type="text/jsx"></script>
</body>
</html>

As you can see the index.html doesn’t contain very much:

  • The <head> contains only standard HTML5 meta tags and the title of the page, nothing React specific.
  • Directly after the <body> we only have a “root” element which is the base for our React app.
  • Before the </body> we can see some JS files which are partially external and internal:
    • react.development.js: Base React-Library
    • react-dom.development.js: React-DOM extension so React can interact with the DOM
    • babel-standalone: Babel is needed so JSX is possible
  • index.js: our React app

index.js

class Hello extends React.Component {
	render() {
		return (
			<div>
				<h1>Hello there!</h1>
				<p>I am a React Component!</p>
			</div>
		);
	}
}

ReactDOM.render(<Hello />, document.getElementById('root'));

So we define a component named “Hello“.
So we can render it via “<Hello />”.
Withing our component we have a render() funktion, which defines what happens when we render our Component.

At the end we just define, that our component “<Hello />” should be rendered into the element with the ID “root”.

So we get the following output after opening our index.html:

It is important, that you cant “just” open the index.html directly. You instead have to create a local web-server due to CORS restricting the embeding of local JS files.

Otherwise you can copy the JS React code directly in the index.html, but thats not good pratice if your project gets bigger and bigger. An easy way to create a “Live Server” is to use the Visual Studio Code Editor and its plugin called “Live Server”.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.