React RouterDOM

Hi All!

So there’s this concept I came across with react router dom that automatically generates a match object which allows you to create more dynamic url’s for sites.

Eduardo Veres made a really helpful post about it here The Hitchhiker’s Guide to React Router v4: [match, location, history] — your best friends!

But things have changed since his post was made in regards to syntax, for example Switch has been replaced by BrowserRouter, and my react was fussy if I didn’t use Routes for multiple/nested links.

In addition to this, I can’t seem to get the match functionality to work, nothing comes up when I try to read from it.

Does anyone have a reference to a working example using the latest react syntax? I tried to follow up on available documentation (See link) but was unable to figure it out. silently prays to god it isn’t just a typo somewhere

As a proof of concept, I put everything in index js to try and get to the heard of the matter - and still no dice…

any help would be greatly appreciated, for now… I need sleep cries

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

import {
  BrowserRouter as Router,
  Routes,
  Route,
  useParams,
  useLocation
} from "react-router-dom";

import Login from './containers/Login';
import Profile from './components/Profile';
import Home from './containers/Home';

function User(props) {
  let params = useParams();
  let location = useLocation();
  console.log(params);
  return <h1>Hello {props.match}!</h1>;
}

ReactDOM.render(
  <Router>
    <Routes>
        <Route path="/login" element={<Login />} />
        <Route path="/home" element={<Home />} />
        <Route path="/user" element={<User />} />
        <Route path='/home/:id' element={<Profile />}/>
    </Routes>
  </Router>,
  document.getElementById('root')
);

Works for me: elegant-tamas-iizy5 - CodeSandbox

1 Like

Would you believe me if I said I spent all night trying to get this to work?

In the end it was because
a) I stopped using dynamic links and had been screen bathing too long to notice
b) I didn’t actually discover the existence of useParams and useLocation till the very end, where my brain was too fried to actually take a second to think.

Appreciate this, thanks!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.