Search code examples
reactjsreact-routerstyled-components

How to change header background color in react based on location


How do I change my headers color based on what route/page I am on in my React project?
I have looked at withRouter but I am not sure how to use the example.
I just want to do something like if the route is not the Home component then change the background color of the header to blue. Seems like it would be simple but can't figure it out.


Solution

  • You can use the location prop that is added to your component by connecting the component to the router via withRouter. From there you apply a conditional style based on which route path you are in.

    import React from 'react'
    import PropTypes from 'prop-types'
    import { withRouter } from 'react-router'
    
    // A simple component that shows the pathname of the current location
    class Header extends React.Component {
      static propTypes = {
        match: PropTypes.object.isRequired,
        location: PropTypes.object.isRequired,
        history: PropTypes.object.isRequired
      }
    
      render() {
        const { match, location, history } = this.props
    
        const headerColor = location.pathname === 'home' ? { background: 'white'} : { background: 'blue' }
        return (
      <div style={headerColor}>You are now at {location.pathname}</div>
      )
    }
    }
    
    // Create a new component that is "connected" (to borrow redux
    // terminology) to the router.
    const AdaptiveHeader = withRouter(Header)
    
    export default AdaptiveHeader
    

    For the above example I repurposed the code found here.