Into the Deep End
Learn to implement your first React component.
We have just talked about the “what,” “when,” and “where” but we have not yet talked about the"how.” Let’s explore that now and write our first React component. In order to display our component in the browser, we need to install not only React, but also ReactDOM, a package that enables us to mount our application in the browser (to use it in the browser). Let’s take a look at a very minimalist setup to get started with React:
<!DOCTYPE html><html><head><meta charset="UTF-8" /><title>Hello React!</title></head><body><div id="root"></div><script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script><script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script><script>// Placeholder for our first component</script></body></html>
We build up the bare-bones setup for a regular HTML document and load it in React and ReactDOM in their latest stable
version from unpkg-CDN
. We can now use React and ReactDOM as a global variable in the window object as a window. React
and window.ReactDOM
. Apart from that, we only see an empty page here with an empty: <div id="root"></div>
<div id="root"></div>
As you can see, we get an empty page with the given code because there was nothing inside the div
tag. This div
will be used as our mount node to show our first React component.
Note: We normally refer to this as an app, web app, or single page app if we deal with several React components. The boundaries of when we call a component an app are fluid. Some developers may consider our code an app even if it has just a single component. Some would say that there needs to be multiple components in an app. However, one clear definition of an does not exist.
First React component
Let’s start with a classic “Hello World” example and include the script where we put the placeholder
earlier.
class HelloWorld extends React.Component {
render() {
return
...