Home > Software design >  Performing a condition based on the current URL with react.js and react router v6
Performing a condition based on the current URL with react.js and react router v6

Time:03-21

Using React.js & react router v6

Is there a way I can extract information from the current URL? Let's say my current URL is this: localhost:3000/about/x567gfh67ssd90g

I simply want to perform a condition based on the current URL. Is there any possible way of doing this?

CodePudding user response:

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

const Component = () => {
  const location = useLocation();
  useEffect(() => {
    console.log(location);
  });
  return ();
};

You can get pathname using useLocation.

CodePudding user response:

You can also add connected-react-router to your project. This way you will have access to all the current route information in your redux-store. This will also allow you to "Time travel" through your SPA. When you hit the backbutton instead of going to the previous page you can go back through state.

import React from 'react';
import { render } from 'react-dom';
import { Provider, ReactReduxContext } from 'react-redux';
import { ConnectedRouter } from "connected-react-router";
import { store, history } from './Store/store';
import { App } from './App/App';

render(
    <Provider store={ store } context={ ReactReduxContext } >
        <ConnectedRouter context={ ReactReduxContext } history={ history }>
                <App />
        </ConnectedRouter>
    </Provider>,
    document.getElementById('app')
);

If you install the redux-devTools in your browser you can look at all the URL data like this- Obviously this is a little more advanced but you it will give you access to everything you need.

enter image description here

  • Related