Reputation:
I'm understanding the react-router-dom library and the components that provide the routing and noticed a strange behavior as below.
Assume we have our App.js component which return JSX code as below.
import './App.css';
import ColorAdder from './ColorAdder';
import {Switch,Route} from 'react-router-dom';
function App() {
return (
<Switch>
<ColorAdder/>
<Route path="/hello" exact>
<p>Hello</p>
</Route>
</Switch>
);
}
export default App;
Now the component ColorAdder.js
also consists of Routes with Path
and exact
attributes declared as below.
import { Route } from "react-router-dom";
const ColorAdder = ()=>{
return (
<Route path="/hi" exact>
<p>Hi</p>
</Route>
)
}
export default ColorAdder;
The App.js is wrapped with <BrowserRouter>
and what i noticed is when we test the page with url http://localhost:3002/hi
it returned Hi as expected but it does n't return anything for 'http://localhost:3002/hello'.why does it behave this way ? Can anyone please explain this behavior why the Route
with path hello
is not identified even when it is under Switch
wrapping and with Path
and exact
attributes
Below is the Index.js
using BrowserRouter
ReactDOM.render(<BrowserRouter><App/></BrowserRouter>,document.getElementById('render'))
Versions: react-router-dom@5, npm - 7.20.3, node - v16.7.0
Upvotes: 0
Views: 1437
Reputation: 480
First, it's good practice to have routing logic in app.js plus don't render <ColorAdder/>
inside the switch instead use the component attribute in <Route />
like this:
your App.js : -
import './App.css';
import ColorAdder from './ColorAdder';
import {Switch,Route} from 'react-router-dom';
function App() {
return (
<Switch>
<Route path="/hi" component={colorAdder} exact></Route>
// if you have other routes do like this
<Route path="/hello" component={<p>hello</p>} exact></Route>
// instead of hard coding <p>hello </p> here you can create a separate component that render the helloComponent
</Switch>
);
}
Your ColorAdder.js: it should only return the content because the routing logic is done in app.js
import { Route } from "react-router-dom";
const ColorAdder = ()=>{
return (
<p> h1 </p>
)
}
export default ColorAdder;
NB: BrowserRouter should be inside index.js, it should wrap the app component.
<BrowserRouter>
<App />
</BrowserRouter>,
Upvotes: 1