In index.js, set two variables equal to the two React modules we downloaded in my last post, react and react-dom. The syntax for loading a module is require(insert-module-name).
On line 4, we’ll define our first React component and set it to a new variable, HelloWorld. We’ll start without using ES6, in which case you can use the createClass helper to initialize a component class. Every React component includes a render function that returns the HTML you want to display in the DOM.
On line 12, we use the render method from the the ReactDOM module to update the DOM with the output from our HelloWorld component/function. We pass it the component first, the selected element last.
Next run npm run start to start the development server, visit http://localhost:8080/ and you’ll see “Hello World!” displayed.
It’s always worth using a web inspector to see what’s being rendered in the DOM.
As expected, the HelloWorld component has rendered inside the app. Note how the div element we rendered was automatically assigned a data-reactroot attribute. This allows tools like react-detector to identify a React app without any hiccups.
In my next post, I’ll demonstrate how functional components and props are used to organize your UI into reusable, isolated building blocks. All react components are pure; they always return the same result given the same arguments and never change the state of variables outside of their scope (no side effects!). This makes React components easy to test.