Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: t.useContext(...) is null error in react router Link (React + Webpack)

I have a project of react + django + webpack. I defined Routes on my App.js

<NavBar />
<Router>
  <Routes>
    <Route exact path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>

I defined Links in my NavBar.js component:

import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

If I used Link in App.js it works normally but when I use it in the component NavBar.js I get this error:

enter image description here

WebPack config:

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
    publicPath: '/',
  },
  stats: {
    errorDetails: true,
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  devServer: {
    historyApiFallback: true,
  },
  plugins: [
    new webpack.DefinePlugin({
      "process.env": {
        // This has effect on the react lib size
        NODE_ENV: JSON.stringify("production"),
      },
    }),
  ],
  performance: {
    hints: false,
    maxEntrypointSize: 512000,
    maxAssetSize: 512000
  }
};

I tried using Switch as well but it only worked using hyperlinks <a>.

like image 494
TF Ryzen Avatar asked Sep 01 '25 10:09

TF Ryzen


1 Answers

You are rendering the Link components outside the routing context provided by Router component. Move NavBar into the routing context.

<Router> // <-- provides routing context
  <NavBar /> // <-- inside routing context
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/about" element={<About />} />
  </Routes>
</Router>

Or using a layout route:

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

const AppLayout = () => (
  <>
    <NavBar />
    <Outlet />
  </>
);
<Router>
  <Routes>
    <Route element={<AppLayout />}>
      <Route path="/" element={<Home />} />
      <Route path="/about" element={<About />} />
    </Route>
  </Routes>
</Router>
like image 78
Drew Reese Avatar answered Sep 04 '25 05:09

Drew Reese