Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Created Sep 13, 2019
Embed
What would you like to do?
React routing using package 'react-router-dom'
import React, {Component} from 'react';
import Header from './component/header';
import Main from './containers/main';
class App extends Component {
render() {
return (
<React.Fragment>
<Header />
<main className="container">
<Main />
</main>
</React.Fragment>
);
}
}
export default App;
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import {withRouter} from 'react-router-dom';
class Header extends Component {
render() {
return (
<React.Fragment>
<header>
<ul>
<li className={this.props.location.pathname === "/" ? "active" : ""}><Link to="/">Home - Redux Demo</Link></li>
<li className={this.props.location.pathname === "/about" ? "active" : ""}><Link to="/about">About</Link></li>
<li className={this.props.location.pathname === "/contact" ? "active" : ""}><Link to="/contact">Contact</Link></li>
</ul>
</header>
</React.Fragment>
)
}
}
export default withRouter(Header);
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>
, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import Home from './../pages/home';
import About from './../pages/about';
import Contact from './../pages/contact';
const Main = () => (
<Switch>
<Route exact path='/' component={Home}/>
<Route exact path='/about' component={About}/>
<Route exact path='/contact' component={Contact}/>
</Switch>
)
export default Main;
@ankitkanojia

This comment has been minimized.

Copy link
Owner Author

@ankitkanojia ankitkanojia commented Sep 13, 2019

Need to install a package of the router for routing.

### npm i react-router-dom

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment