I am facing an issue with rendering a component using React Router in my React TypeScript application. Specifically, I have a <nav>
element that contains a link, and I want to navigate to the AddTask
component when the link is clicked. The problem is that when I attempt to modify the code by removing the <nav>
wrapper or replacing it with a <div>
or <Router>
, the component fails to render successfully. It only renders properly when the <nav>
covers the entire application.
I would greatly appreciate any insights or suggestions on how to resolve this issue. Is there a specific configuration or modification that I need to make to ensure successful rendering of the AddTask component without having the <nav>
cover the entire app?
Here is the code that runs successfully it displays a simple navbar
import { Component } from 'react';
import { Routes, Route, Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import 'bootstrap/dist/js/bootstrap.js';
import AddTask from './components/addtask';
import './App.css';
class App extends Component{
render() {
return (
<nav className="navbar navbar-expand navbar-dark bg-dark">
<div className="navbar-nav mr-auto">
<a className="navbar-brand" href="#">Add</a>
</div>
</nav>
);
}
}
export default App;
When I modify the code to the following, it doesn’t render.
import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.js';
import AddTask from './components/addtask';
import './App.css';
class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-expand navbar-dark bg-dark">
<div className="navbar-nav mr-auto">
<Link to="/add" className="navbar-brand">Add</Link>
</div>
</nav>
<Router>
<Routes>
<Route path="/add" element={<AddTask />} />
</Routes>
</Router>
</div>
);
}
}
export default App;
2
Answers
You shouldn’t use
Router
directly according to the docs. UseBrowserRouter
orHashRouter
instead.The Router components provide the context for React Router, so all React Router components need to be rendered inside of one of those. You probably want the router to wrap your whole application. E.g.
Issue
The only issue I see with the code and can reproduce in a running sandbox is the
Link
being rendered outside a routing context.Solution
Wrap the
nav
element inside theRouter
component so theLink
components it renders have a routing context available to them from higher up the ReactTree.Example: