First we need to install new app using create-react-app

npm install -g create-react-app

create-react-app introRouter

cd introRouter

npm start //to start app

install the react-router-dom

npm i --save react-router-dom

Now create a router folder in src directory

In router folder create new file with name router.js

add the below code in router.js file just we created

We only import Route Component from react-router-dom to create routes for our App

import React from "react"; import { Route } from "react-router-dom"; import App from "../components/App"; import Posts from "../components/Posts"; import Header from "../header"; const ReactRouter =()=>{ return ( <React.Fragment> <Header /> <Route exact path="/" component={App} /> <Route path="/posts" component={Posts} /> </React.Fragment> );} export default ReactRouter;

we added exact it tells to load only these component

Now create components folder in src directory/folder

Delete App.js file in your src folder

Add new App.js in the Components Folder

Add below code in your App.js file

import React, { Component } from "react"; class App extends Component { render() { return ( <div style={{ textAlign: "center", marginTop: "10rem" }}> <h1>App is there</h1> </div> );}} export default App;

Create new file with name Posts.js

Add the below code

import React, { Component } from "react"; class Posts extends Component { render() { return ( <React.Fragment> <div style={{ textAlign: "center",marginTop:'10rem' }}> <h1>Posts is there</h1> </div> </React.Fragment> );}} export default Posts;

Now create a header.js file in your Src directory/folder

Add below code . we are importing Navlink from react-router-dom

to create link tags

import React, { Component } from "react"; import { NavLink } from "react-router-dom"; class Header extends Component { active = { fontWeight: "bold", color: "red" }; header = { display: "flex", justifyContent: "space-evenly", listStyle: "none" }; render() { return ( <div style={this.header}> <NavLink exact to="/" activeStyle={this.active}> Home </NavLink> <NavLink to="/posts" activeStyle={this.active}> Posts </NavLink> </div> );}} export default Header;

Above Header component we already included in router.js file

Now go to index.js file and remove the previous code and add these

below code

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import {BrowserRouter as Router} from 'react-router-dom'; import ReactRouter from './router/router';

ReactDOM.render(

<Router> <ReactRouter/> </Router>,document.getElementById('root'));

These makes our index.js very less code and no confusion

We already separated router.js and header.js

Checkout React router beginners guide

Github repository for code