Tutorials React

Install react-router-dom module

npm i react-router-dom@4.3.1

Now import react-router-dom in index.js

 import {BrowserRouter} from 'react-router-dom'; 

wrap app component with <BrowserRouter>

 ReactDOM.render(
  <React.StrictMode>
   <BrowserRouter><App /></BrowserRouter>  
  </React.StrictMode>,
  document.getElementById('root')
); 

Now import Router from react-router-dom in app.js

 import {Router} from "react-router-dom";

Now define Routes by giving path and component name

<Route path="/products" component={Products} />  

Now visit in browser localhost:3000/products and check if product component is rendered.

If it is not rendered try via using render attribute

<Route path="/products" render={props => <Products/>} /> 

https://tylermcginnis.com/react-router-pass-props-to-components/

exact keyword in route component

It is used to defined exact path.. for example in a module if path is exactly /home then render home component.

Now in app.js

However In Contrast to / one can use Switch component

 import { Router, Route, Switch } from "react-router-dom"; 
 <Switch>
        <Route path="/about" component={About} />
        <Route path="/services" component={Services} />
        <Route path="/contact" component={Contact} />
        <Route path="/home" component={Home} />

        <Redirect from="/" exact to="/home" />
        <Redirect to="/not-found" />
</Switch> 

Switch component render the first child that matches. Switch component basically checks routes orderly. For example in above snippet first it matches the path with about, then services, then contact, then home, and if it not find anything from these in url it checks for simple / , will redirect home page. If url is /sdmnfbjreb which is not matched with any of the defined routes then it redirect to not-found

Passing additional parameters to Route Component

 <Route
              path="/products"
              render={props => <Products sortBy="newest" {...props}/>}
 /> 

How to pass router parameter to Route

  <Route path="/products/:id" component={ProductDetails}/> 

In link

<Link to={`/blog/${post.id}`} className="btn btnprimary">Read More           </Link>

getting value of router parameter in component

{this.props.match.params.id}

Make Router Parameter optional, by appending question mark at the end of parameter

 <Route
              path="/posts/:year?/:month"
              render={props => <Posts {...props} isAuthed={true} />}
            /> 

value can be accessed same as

 Year: {match.params.year}, Month:{match.params.month}

Query String

passing query string to a url parameter

parameter is in location

npm i query-string@6.1.0

import queryString from ‘query-string’;

const result = queryString.parse(location.search);  console.log(result);

Leave a comment