Now that we have the project setup, let's get something basic on the page. Let's put a paragraph on the page with "Hello, world!" in it.
We need to download two new dependencies: React and React DOM. React is the library that handles the virtual DOM manipulation. React DOM handles the actual manipulations to the DOM in the brower. This is separated due to other implementations of React rendering such as React Native for native app development.
Install the dependencies with the following command:
Table of Contents
yarn add react react-dom // npm install --save react react-dom
src/app.js, remove the
console.log call. Next we need to import React and React DOM into this file so we can use them. Add the following to the top of this file.
import React from 'react'; import ReactDOM from 'react-dom';
This will bring in the libraries we need. Next, we need to grab an element to use as the root of our project. Luckily we have one already on our
index.html file. It has an
app-container. So let's grab it.
const root = document.getElementById('app-container');
Now we have a container to put our application in. Now we will use
ReactDOM to render a paragraph inside this container.
ReactDOM.render(<p>Hello, world!</p>, root);
ReactDOM.render(React.createElement('p', null, 'Hello, world!'), root);
We could write all our code like it is above, but it's much easier to write it in JSX and let Babel handle the heavy work. It makes our code much easier to read and maintain in the future.
If you view the application in the browser, you will see "Hello, world!" displayed on the screen.
Now that we know how to put something on screen, let's create our first component!