Let's create a React application and then add React-Router as a dependency.
To create a React application, we will use the create-react-app CLI. The create-react-app CLI makes it easier to create an application that already works. The CLI creates a project scaffold so that you can start using the latest JavaScript features, and also provides scripts to build applications for a production environment. There are various React and React-Router starter kits available; however, using create-react-app helps in demonstrating how React-Router can be added to an existing bare-bones React application.
The first step is to install create-react-app globally using NPM, as follows:
npm install -g create-react-app
The CLI requires the node version to be greater than or equal to 6, and the npm version to be greater than 5.2.0.
Once the CLI has been installed, we will create a new application using the create-react-app command, as seen here:
create-react-app react-router-demo-app
The following output is displayed when create-react-app completes the installation of packages:
Inside that directory, you can run several commands:
npm start
Starts the development server.
npm run build
Bundles the app into static files for production.
npm test
Starts the test runner.
npm run eject
Removes this tool and copies build dependencies, configuration
files
and scripts into the app directory. If you do this, you can't
go back!
We suggest that you begin by typing:
cd react-router-demo-app
npm start
If you used the yarn package manager (https://yarnpkg.com/en/), the npm commands in the preceding snippet would be replaced with yarn.
The react-router-demo-app directory is created during installation (if it doesn't already exist). Inside the directory, the following project structure is created:
/react-router-demo-app
|--node_modules
|--public
| |--favicon.ico
| |--index.html
| |--manifest.json
|--src
| |--App.css
| |--App.js
| |--App.test.js
| |--index.css
| |--index.js
| |--logo.svg
| |--registerServiceWorker.js
|--package-lock.json
|--package.json
|--README.md
The CLI installs all the necessary dependencies, such as Babel, to transpile ES6 code to ES5, thus enabling you to leverage the latest JavaScript features. It also creates a build pipeline configuration with the help of webpack. Post-installation, no additional configuration is required to start or build the app. As noted in the preceding output, you can start the app using the npm start command and build a production-ready app using npm build.
On running npm start, the application is compiled and will open a browser window with a Welcome to React message displayed, as shown here:
In the index.js file, the ReactDOM reference is used to render the application's root component as follows:
ReactDOM.render(<App />, document.getElementById('root'));
The <App> component marks the beginning of the tree that will get rendered when the application starts.