Adam
Adam

Reputation: 677

Component not loading when i change link in nested route in react-router

I have the following code inside ComponentA

        <BrowserRouter> 
          <Switch>
            <Route exact path="/"> <ComponentB /> </Route>
            // More Routes are here
          </Switch>
        </BrowserRouter>

I have the following code inside ComponentB

          <NavLink to="/campaigns">CLICK HERE</NavLink> 
          <Switch>
            <Route exact path="/"> <Dashboard /> </Route>
            <Route path="/campaigns"> <Campaigns /> </Route>
          </Switch>

What I want is to have "Dashboard" component rendered inside ComponentB by default. And if someone clicks on the "CLICK HERE" link, "Dashboard" component should be replaced by "Campaigns" component.

But what is happening now is that when someone clicks on "CLICK HERE", the url in addressbar changes to "localhost:3000/campaigns" as I want to, but "Campaigns" component is not loaded. Instead a blank page appears.

What am I doing wrong?

Please ask if I should make my question more clear. Thanks!

Upvotes: 1

Views: 113

Answers (2)

P. Brew
P. Brew

Reputation: 777

Try defining your routes as follows:

<Route path="/campaigns" render={Campaigns} exact />

The "exact" may or may not be necessary.

Upvotes: 0

Jurrian
Jurrian

Reputation: 849

You shouldn't use react-router if you don't want to change the route. Just use JS. I'd use state to save which tab is active, and just show the active one.

const [output, setOutput] = useState('dashboard');

return (
  <div>
    <div>
      <button onClick={() => setOutput('dashboard')}>Dashboard</button>
      <button onClick={() => setOutput('campaigns')}>Campaigns</button>
    </div>
    {output === 'dashboard' ? <Dashboard /> : <Campaigns />}
  </div>
);

Upvotes: 1

Related Questions