Reputation: 393
I am new with React JS so I am sorry if this problem seems trivial.
I have set up a <Switch>
along with a number of Routes
in App.js to redirect and link components together. The first <Redirect>
from App.js goes to ComponentA
where when a div is clicked, it should go to ComponentB
, but that is not the case. After some fiddling, I could get ComponentB
to render but it was ALONG with ComponentA
, and now with more changes, nothing shows up except the header .../componentB
.
App.js
import { ComponentA, ComponentB } from './components/Component.js';
import { BrowserRouter as Router, Route, Redirect, Switch} from 'react-router-dom';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<Router exact path="/">
<Switch>
<Route exact path="/componentA" component={ComponentA}/>
<Route exact path="/componentB" component={ComponentB}/>
<Route exact path="/componentC" component={ComponentC}/>
</Switch>
{isLoggedIn ? <Redirect to="/componentA"/> : <Redirect to="/componentC"/>}
// componentC is irrelevant to the question
</Router>
</div>
);
}
ComponentA
import { BrowserRouter as Router, Route, Redirect, Switch} from 'react-router-dom';
function ComponentA() {
return (
<div>
<Router exact path="/">
// ... code
<Link exact to="/componentB">
<div></div>
</Link>
</Router>
</div>
);
}
ComponentB (in the same file as ComponentA)
function ComponentB() {
return (
<div>Welcome to ComponentB</div>
);
}
Upvotes: 2
Views: 3327
Reputation: 202751
I think the second Router
component rendered in ComponentA
is jacking the link navigation. This "inner" routing context handles the navigation request and updates the URL in the address bar but doesn't allow the "outer" routing context to see the change and update the Route
that is matched and rendered.
Remove the Router
in ComponentA
, also remove the exact
prop from the Link
as it's not a link prop.
import { Link } from 'react-router-dom';
function App() {
return (
<div>
// ... code
<Link to="/componentB">
<div></div>
</Link>
</div>
);
}
Remove the exact
and path
props from Router
, these are props for Route
components.
import { ComponentA, ComponentB } from './components/Component.js';
import { BrowserRouter as Router, Route, Redirect, Switch} from 'react-router-dom';
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<Router>
<Switch>
<Route exact path="/componentA" component={ComponentA}/>
<Route exact path="/componentB" component={ComponentB}/>
<Route exact path="/componentC" component={ComponentC}/>
</Switch>
{isLoggedIn ? <Redirect to="/componentA"/> : <Redirect to="/componentC"/>}
// componentC is irrelevant to the question
</Router>
</div>
);
}
You need only one routing context for your application, typically a Router
that wraps App
component. Comb your code for any other nested Router
components and remove them as these will mess with navigation as explained above.
Upvotes: 1