Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How properly setup react-router-dom in Home Route?

I have this index.js:

<Provider store={store}>
  <Router history={history}>
    <App/>
  </Router>
</Provider>

this App.js:

<Switch>
  <Route exact path="/" component={Home} />
    <Route
      path="/login"
      render={() => <Login userError={this.state.userError} />}
    />
  <Route path="/registration" component={Registration} />;
</Switch>

and Home.js:

<div className="Home">
  <Header/>
  <div className="content">
    <Sidenav/>
      <Switch>
        <Route path="/friends" component={Friends}/>
      </Switch>
    <Feed/>
  </div>
</div>

I want Friends component to be rendered inside content block, but now if I try to reach /friends route via Link I am getting blank page. If I set /friends Route in App.js, it will be OK, but I won't have it in my content class, because it will be another page.

May you give me a hand with that?

Also in feature I will be have more items to display in content, that's why I put Switch in Home.js

Thanks in advance!

like image 905
Nikita Shchypyplov Avatar asked Mar 06 '23 19:03

Nikita Shchypyplov


1 Answers

Move your content class and <Friends>

The issue you're having is that the component Home is not rendering when you visit /friends because it will only render when you go to /

To fix this just move the Route into the App.js file, along with the content class into the Friends component.

To make this easier, you could make your content class into a component. This way you could wrap it around all of the stuff you render.


Or move <Friends> and wrap content

What I mean by this is that you could also create your own Route component that wraps whatever component passed to it in a Content component. It might look similar to this:

const ContentRoute = ({ component, ...props }) => (
  <Route {...props} component={() => (
    <Content>
      <component />
    </Content>
  )}>
  </Route>
)
like image 75
Andria Avatar answered Mar 09 '23 07:03

Andria