I'm trying to use the useParams() react hook to retrieve a parameter, but I'm getting this error:
TypeError: useContext(...) is undefined
This error is actually thrown by the hooks file, specifically this line (line 40):
/modules/hooks.js:40
39 |
> 40 | const match = useContext(Context).match;
41 | return match ? match.params : {};
42 | }
My App.js file that contains the routing logic looks like this:
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { ThemeProvider } from "@material-ui/core";
import theme from "./views/config/theme";
import { routes } from "./views/config/routes";
import Header from "./views/components/common/Header";
import Footer from "./views/components/common/Footer";
function App() {
return (
<div>
<ThemeProvider theme={theme}>
<Router>
<Header />
<Switch>
{routes.map((route) => (
<Route exact path={route.path}>
{route.component()}
</Route>
))}
</Switch>
<Footer />
</Router>
</ThemeProvider>
</div>
);
}
export default App;
The routes.js file that contains all the routes looks like this:
import Dashboard from "../pages/Dashboard";
import UserDetails from "../pages/UserDetails";
export const routes: [
{
name: "Dashboard",
path: "/dashboard",
component: Dashboard,
access: "public",
},
{
name: "User details",
path: "/user/:id",
component: UserDetails,
access: "private",
},
];
and this is the UsersDetails component file where I'm trying to use the useParams() hook, it looks like this:
import { useParams } from "react-router-dom";
const UserDetails = () => {
const { id } = useParams();
return (
<div>
<p>{id}</p>
</div>
);
};
export default UserDetails;
I'm using:
NodeJS - 14.17.0
and:
"react": "^17.0.2"
"react-dom": "^17.0.2"
"react-router": "^5.2.0"
"react-router-dom": "^5.2.0"
"react-scripts": "4.0.3"
1. Setting Routes
Firstly, in routes => component must be wrapped in open-close angle brackets. For example, my routes will look like this:
const routes = [
{
name: "Dashboard",
path: "/dashboard",
component: <Dashboard />,
access: "public",
},
{
name: "User details",
path: "/user/:id",
component: <UserDetails />,
access: "private",
},
];
2. Creating Two Components For Testing
Next, I created two components like this:
const Dashboard = () => {
return <h2>Dashboard</h2>;
}
const UserDetails = () => {
let { id } = useParams();
return <div style={{ fontSize: "50px" }}>
User Detail {id}
</div>;
}
3. Wrapping The App Component
In App Component, we don't need to call component function (route.component() ), For example, look like this:
const App = () => {
return (
<Router>
<div>
<Header />
<Switch>
{routes?.map((route) => <Route path={route.path}>
{route.component}
</Route>)}
</Switch>
</div>
</Router>
);
}