2

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?

2
  • 1
    Im not sure if I understood the question, but you can use useParams to extract the URL parameters, then render the proper component based on them. Commented Feb 15, 2021 at 16:48
  • 1
    Are you talking about query (?foo=bar) or path (/bar) parameters? Commented Feb 15, 2021 at 16:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.