props are not accessible in the function component

Viewed 782

Inside user.js file the props are coming as empty I am unable to access the match in props. I don't understand why props is coming as empty object.

App.js file

import "./App.css"
import { BrowserRouter as Router, Route, Routes, Link } from 'react-router-dom'

import Home from "./components/Home";
import About from "./components/About";
import User from "./components/User";


function App() {

  return (
    <div className="container">
      <Router>
        <ul>
          <li>
            <Link to="/">Home</Link>
          </li>
          <li>
            <Link to="/about">About</Link>
          </li>
          <li>
            <Link to="/user/john">User</Link>
          </li>
        </ul>
        <div>
          <Routes>
            <Route exact path="/" element={<Home/>}></Route>
            <Route exact path="/about" element={<About/>} ></Route>
            <Route exact path="/user/:name" element={<User/>}></Route>
          </Routes>
        </div>
      </Router>


    </div>
  );
}

export default App;

user.js file

import React from 'react'

function User({match}){
    return (
        <div>
            User - {match.params.name}
        </div>
    )
}

export default User

Inside user.js file the props are coming as empty I am unable to access the match object in props. I don't understand why props is coming as empty object.

2 Answers

The User component isn't passed any props:

element={<User/>} // <-- no props are passed to User

With the way routed components are rendered in react-router-dom v6.x now they no longer are passed props (history, location, and match, or any others) and these must now be accessed via their respective hooks.

However, the route params accessed directly via the useParms hook!

For a give route:

<Route exact path="/user/:name" element={<User/>} />

User can use the useParams hook to access the name route path parameter:

import React from 'react';
import { useParams } from 'react-router-dom';

function User() {
  const { name } = useParams();

  return (
    <div>
      User - {name}
    </div>
  )
}

You have to use the hook useMatch hook to access the current match.

Related