0

I have a component with a Nav on the left side and different content on the right side. When the component "MyBookingsOverview" is loaded, I would like to set the first NavItem as active and redirect to this route. I wasn't able to find a way yet. Does anyone has a tip? Here my code:

export default class MyActivities extends Component {  
    render() {
        return (
            <Grid fluid>
                <Col lg={2}>
                    <Nav />
                </Col>
                <Col lg={10}>
                    <Routes />
                </Col>
            </Grid>                 
        );
    }
}

export default class MyActivityNav extends Component {  
    render() {
        return (
            <div className="itemRequestNav">
                <Nav bsStyle="pills" stacked>
                    <LinkContainer to={routes.ACCOUNT_ACTIVITIES_OVERVIEW}>
                        <NavItem>Übersicht</NavItem>
                    </LinkContainer>
                    <LinkContainer to={routes.ACCOUNT_ACTIVITIES_REQUESTS}>
                        <NavItem>Anfragen</NavItem>
                    </LinkContainer >
                    <LinkContainer to={routes.ACCOUNT_ACTIVITIES_BOOKINGS}>
                        <NavItem>Buchungen</NavItem>
                    </LinkContainer >
                </Nav>
            </div>                            
        );
    }
}
export default ({ childProps }) =>
    <Switch>
        <PrivateRoute exact path={routes.ACCOUNT_ACTIVITIES_OVERVIEW} component={MyRequests} />
        <PrivateRoute exact path={routes.ACCOUNT_ACTIVITIES_BOOKINGS} component={MyRequests} />
        <PrivateRoute exact path={routes.ACCOUNT_ACTIVITIES_REQUESTS} component={MyRequests} />  
    </Switch>;

Greetings, Michael

1 Answers1

0

If you want to do conditional styling to a link in your Nav, you have to use the NavLink component from react-router and set the activeClassName prop with your css class.

<Nav bsStyle="pills" stacked>
  <NavLink to={routes.ACCOUNT_ACTIVITIES_OVERVIEW}
    activeClassName="selected">
    <NavItem>Übersicht</NavItem>
  </NavLink>
  <NavLink to={routes.ACCOUNT_ACTIVITIES_REQUESTS}
    activeClassName="selected">
    <NavItem>Anfragen</NavItem>
  </NavLink>
  <NavLink to={routes.ACCOUNT_ACTIVITIES_BOOKINGS}
    activeClassName="selected">
    <NavItem>Buchungen</NavItem>
  </NavLink>
</Nav>

Once you are redirected to the correct component that matches your Route, it will be automatically selected and your style will be applied to that NavLink.

If you need to redirect programmatically to another route have a look at this SO question.

c-chavez
  • 7,237
  • 5
  • 35
  • 49