React Router: change component based on current page


I’ve been looking at this tutorial:

and my current setup is pretty similar to that example.

The structure of my app right now is basically:

        <div className="App">

            <Route exact path="/" render={pageOne} />
            <Route path="/pagetwo/" render={pageTwo} />

And then <Link> components inside pageOne and pageTwo to link to each other

How might I make Header's height change based on the current page? I want Header to show up on each “page”, and not have to re-render it when changing pages, but I want it to show up with a smaller height on pageTwo than on pageOne.

Is there any easy way to do this? One thing I could do is apply CSS attributes to the Header with JavaScript code, but that doesn’t seem very elegant.

Any help would be appreciated!


What method are you using to style your components? I like styled-components as it makes markup cleaner, it’s very familiar for the most part as simple CSS (SASS), and then there’s more, added jsx logic.

I would pass a prop to your header based on which route component is true.

const Header = styled.header`
    height: ${props => (props.headerHeight ? '2rem' : '6rem')};

<Header headerHeight={this.props.headerHeight}>
    Header content.

It should be easy to place a < Link > component on any view as long as you have set up your routes and make sure to add:

import { Link } from 'react-router-dom'

to the top of your code on each view or the components that contain your links.

Let me know if that helps :slight_smile: