fiorentina.gf
fiorentina.gf

Reputation: 57

How to change component in another component when switching to another link?

My App.js:

<Router>
    <Route
        path="/"
        exact
        component={HomePage}
    />

    <Switch>
        <Route path="/register" component={Register} />
        <Route path="/login" component={Login} />
        <Route path="/forgot" component={ForgotForm} />
        <Route path="/reset" component={ResetForm} />
    </Switch>
</Router>

My HomePage looks like that:

<Header />

<Container>
    <Row>
        <Col className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col">
            <SideBar />
        </Col>

        <Col className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
            <SearchDialog />
            <DialogPage />
            <MessagePage />

            //I need to change components in this area when link will be switched
         </Col>
     </Row>
 </Container>

My auth components (register/login/ etc) works perfectly because they don`t need to have sidebar/header like in homepage. HomePage has Sidebar, header and content, which should change when you click on another link. If I place a new Route in App.js with this link, this component will load, but without HomePage.

Upvotes: 0

Views: 434

Answers (1)

Sabbin
Sabbin

Reputation: 2445

You need to have 2 different containers. One public, one private. I created an example below of how this should look like. Adapt it and use it as it fits you.

PS I also added a redirect in your public layout from / to /login

const PublicLayout = () => {
  return(
    <Switch>
        <Route path="/register" component={Register} />
        <Route path="/login" component={Login} />
        <Route path="/forgot" component={ForgotForm} />
        <Route path="/reset" component={ResetForm} />
        <Redirect from="/" to="/login" />
    </Switch>
  )
}

const DefaultLayout = () => {
  return(
    <Header />
    <Container>
        <Row>
            <Col className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col">
                <SideBar />
            </Col>

            <Col className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
                <SearchDialog />
                <DialogPage />
                <MessagePage />

                <Switch>
                  /* Your other routes go here 
                    <Route path="/blaBla" component={blaBla} />                  
                  */
                </Switch>
            </Col>
        </Row>
    </Container>
  );
}


const App = props => {
  const {loggedIn} = props; // Put your login state from where you have it, I put it for example only
  return (
    <Router>
      {loggedIn ? <DefaultLayout> : <PublicLayout>}
    </Router>
  );
}

Upvotes: 1

Related Questions