Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

Adding a class base on the route in react router

I've the following code base.

<Router>
    <Grid className='full-height' fluid>
        <Row>
            <Col xs={6} xsOffset={6} className='top-line' />
        </Row>
        <Row>
            <NavBar />
        </Row>
        <Row>
            <div className='content-wrapper'>
                <Switch>
                    <Route exact path='/' component={Container} />
                    <Route path='/login' component={Login} />
                    <Route path='/register' component={Register} />
                    <Route path='/dashboard' component={Dashboard} />
                    <Route exact path='/packages' component={Packages} />
                    <Route path='*' component={NotFound} />
                </Switch>
            </div>
        </Row>
    </Grid>
</Router>

I would like to add a class to the Grid component based on the route path. Basically what I want is to add a specific class when on path='/' so I can custom style home page. Since the container component is residing inside the content-wrapper I couldn't style it to the way I want.

How can I add a custom class based on the route path in react router?

Upvotes: 3

Views: 4154

Answers (1)

Imesh Chandrasiri
Imesh Chandrasiri

Reputation: 5679

I found a workaround to get the class to be added.

<Router>
                <Route render={(props) => {
                    let HomePageStyling = '';
                    if (props.location === '/') {
                        HomePageStyling = 'landing-page';
                    }
                    return (
                        <Grid className={'full-height' + HomePageStyling} fluid>
                            <Row>
                                <Col xs={6} xsOffset={6} className='top-line' />
                            </Row>
                            <Row>
                                <NavBar />
                            </Row>
                            <Row>
                                <div className='content-wrapper'>
                                    <Switch>
                                        <Route exact path='/' component={Container} />
                                        <Route path='/login' component={Login} />
                                        <Route path='/register' component={Register} />
                                        <Route path='/dashboard' component={Dashboard} />
                                        <Route exact path='/packages' component={Packages} />
                                        <Route path='*' component={NotFound} />
                                    </Switch>
                                </div>
                            </Row>
                        </Grid>
                    );
                }}
                />
            </Router>

Upvotes: 5

Related Questions