×

Html & Html5

The World's best Software Development Study Portal

ReactJS Routing

ReactJS Routing with Examples

First install react routing packages C:\Users\Parveen>npm i [email protected]

Index.js

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import "./index.css"; 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: http://bit.ly/CRA-PWA serviceWorker.unregister();

App.js

import React, {component} from 'react'; import About from './About' import Contact from './Contact' import Home from './Home' import Error from './Error' import Menu from './Menu' import { Route, Switch } from 'react-router-dom'; const App = () => { return ( <div className="tc"> <Menu/> <Switch> <Route path="/" component={Home} exact/> <Route path="/about" component={About}/> <Route path="/contact" component={Contact}/> <Route component={Error}/> </Switch> </div> ); }; export default App;

Menu.js

import React from 'react'; import { NavLink } from 'react-router-dom'; const Menu = () => { return ( <div>

<NavLink exact activeClassName="active-css" to='/'>Home</NavLink> <NavLink activeClassName="active-css" to='/about'>About</NavLink> <NavLink activeClassName="active-css" to='/contact'>Contact</NavLink> <div/> ); }; export default Menu;

Home.js

import React from 'react'; import img from './img.jpg'; const Home = () => { return ( <div> <h1>Hello, My Home Page</h1> <img src={img} className="App-image" alt="image" width="100%" height="500px"/> </div> ); }; export default Home;

About.js

import React from 'react'; const About = () => { return ( <div> <h1>Hello, My About Page</h1> </div> ); }; export default About;

Contact.js

import React from 'react'; const Contact = () => { return ( <div> <h1>Hello, My About Page</h1> </div> ); }; export default Contact;

Error.js

import React from 'react'; const Error = () => { return ( <div> return <h1> Page not Found</h1> </div> ); }; export default Error;