'Using react-router to switch between pages but my props aren't displaying, is this a router version issue?
I'm trying to render props with the code I have written however, only my header shows. My "about" page also displays properly.
This is the warning message that displays when I'm on the home page "index.tsx:25 Matched leaf route at location "/" does not have an element. This means it will render an with a null value by default resulting in an "empty" page."
VScode is also underlining "props", any idea why?
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from "./components/layout/Header";
import Todos from "./components/Todos";
import AddTodo from "./components/AddTodo";
import About from "./components/pages/About";
import "./App.css";
render() {
return (
<Router>
<div className="App">
<div className="container">
<Header />
<Routes>
<Route
path="/"
exact
render={(props) => (
<React.Fragment>
<AddTodo addTodo={this.addTodo} />
<Todos
todos={this.state.todos}
markComplete={this.markComplete}
delTodo={this.delTodo}
/>
</React.Fragment>
)}
></Route>
<Route path="/about" element={<About />}></Route>
</Routes>
</div>
</div>
</Router>
);
}
}
export default App;
Solution 1:[1]
In react-router-dom
v6 the Route
components no longer have render
or component
props, all routes render their components, as JSX, on the element
prop. There is also no longer an exact
prop as all routes are now always exactly matched.
<Routes>
<Route
path="/"
element={
<React.Fragment>
<AddTodo addTodo={this.addTodo} />
<Todos
todos={this.state.todos}
markComplete={this.markComplete}
delTodo={this.delTodo}
/>
</React.Fragment>
}
/>
<Route path="/about" element={<About />} />
</Routes>
VScode is also underlining "props", any idea why?
From what I can tell, the props
aren't being used, so VSCode/linter is likely flagging it as being declared but not used. Hovering over the props
should pop up a small window with the explanation and "buttons" to try and resolve it for you. It's moot though as with what I explained above there is no longer a render
prop to pass a function to.
Solution 2:[2]
This code worked for me.
<Routes>
<Route
path="/"
element={
<React.Fragment>
<AddTodo addTodo={addTodo} />
<Todos
todos={todos}
onDelete={onDelete}
/>
</React.Fragment>
}
/>
<Route path="/about" element={<About />} />
</Routes>
Also, import this at the start
import * as React from 'react'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Ramyashree Shetty |