Pass parameters with React Router

Viewed 49

Im new to React and i have the following app: (index.js)

import ReactDOM from 'react-dom'
import {Component} from 'react';
import './style.css'

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";


import Header from './components/Header'
import Body from './components/Body'
import Footer from './components/Footer'

class App extends Component {
    render() {
        return (
            <div id="layout">
              <Header />
              <Body />
              <Footer />
            </div>
          );
    }
}

ReactDOM.render( <App />, document.querySelector("#root"));

Each time I'm going to localhost:port Im redirected to this componenet, I wanted to use Router and extract the data, for example:

localhost:port/instanceName=value will route me to same compontents with props value only if value is x or y, is that possible?

1 Answers

I suggest you to setup it this way. It is just a custom hook which extract all url parameters.

// use-query-string.js
import { useLocation } from 'react-router-dom';

export const useQueryString = () => {
  return new URLSearchParams(useLocation().search);
};

Then you can call this in your component which gives you a list of query strings in the url. In fact every time you call it, it would give you a list of passed parameters.

const queryString = useQueryString();

And finally you can extract what you want. Simply by passing the name of the parameter you are looking for.

queryString.get('instanceName')

In your case it could be something like this.

import { useQueryString } from 'use-query-string';
class App extends Component {
   
   const queryString = useQueryString();

   useEffect(() => {
     const value = queryString.get('instanceName');
     
     if (value === 'x') {
       // do this
     } else if (value === 'y') {
       // do that
     }
     
   }, [queryString])

    render() {
        return (
            <div id="layout">
              <Header />
              <Body />
              <Footer />
            </div>
          );
    }
}

But keep in mind that your url should be like localhost:port?instanceName=value. Actually instead of / at the end you need to put ?. I am not sure if it works with / as well. You can test and tweak if it does not.

Related