Skip to content

Instantly share code, notes, and snippets.

@ankitkanojia
Created September 13, 2019 10:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ankitkanojia/90cea58257bb986b69f36cf7f3ccd584 to your computer and use it in GitHub Desktop.
Save ankitkanojia/90cea58257bb986b69f36cf7f3ccd584 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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