react js router tutorial

After getting started with basics of react, I was looking for how to do routing using react. Most widely use packages are react-router, react-router-dom. Here is simple code that will get you started using react-router-dom.

Step#1
Create a simple react app using creae-react-app command. You can refer to getting started with react post to get you stared.

$ create-react-app todolist

Step#2
Here is my index.js file edited for router.

import React from 'react'  
import ReactDOM from 'react-dom';  
import { BrowserRouter, Route } from 'react-router-dom'  
import Layout from './Layout';  
import Header from './Header';  
import Footer from './Footer';

class App extends React.Component {  
  render() {
    return (
        <div>
          <h1>hello new </h1>
        </div>
    )
  }
}

class About extends React.Component {  
  render() {
    return (
        <div>
          <h1>This is About Page</h1>
        </div>
    )
  }
}

//export default App

ReactDOM.render((  
<BrowserRouter>  
    <div>
      <Route exact path="/" component={App} /> {/* Note-1 */}
      <Route path="/header" component={Header} />
      <Route path="/footer" component={Footer} />
      <Route path="/Layout" component={Layout} />
      <Route path="/About" component={About} />
    </div>
</BrowserRouter>

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

Please find below sample file for Header. Footer and Layout files will be similar.

import React from 'react';

class Header extends React.Component {  
  render() {
    return (
      <div >
        <h1>This is Header</h1>
      </div>
    );
  }
}

export default Header;  

As per GitHub issue response, if you are using react-router-dom, you done need to import react-router (at least 99.99 % of time).

Reference Posts:
https://stackoverflow.com/questions/42984597/multiple-nested-routes-in-react-router-dom-v4

https://stackoverflow.com/questions/43008036/the-prop-history-is-marked-as-required-in-router-but-its-value-is-undefine

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.