Home > OS >  React router, inferred query string
React router, inferred query string

Time:12-14

I do realize this might be a bad practice, but I need to redirect a user according to their email in exactly this manner:

/chat?user={emailAddress}

What should the exact path look like so that I could access emailAddress as a prop in chatRenderer ? URL must have name query in it.

   <Route
     exact
     path={`/chat?user=???`}
     render={this.chatRenderer}
   />

CodePudding user response:

App.js

<Route
     exact
     path="/chat"
     component={UserChatPage}
   />

Home page

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

function MyHomePage (){

const history = useHistory()

const redirect = ()=> history.push(`/chat?user=${email}`);

User chat page

var url_string = window.location.href
var url = new URL(url_string);
var user = url.searchParams.get("user");

CodePudding user response:

react-router-dom concerns itself only with matching the path part of the URL.

Change the Route to match the URL sans the queryString:

<Route
  path="/chat"
  render={this.chatRenderer}
/>

In the routed component access the queryString search from the location object. location is available on props if rendered by render or component prop of Route, or can be accessed by the useLocation hook.

const { search } = location;

...

const searchParams = new URLSearchParams(search);
const userEmail = searchParams.get('user');

// apply logic against userEmail value
  • Related