thomasna82
thomasna82

Reputation: 143

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.

Upvotes: 2

Views: 5670

Answers (2)

Chase DeAnda
Chase DeAnda

Reputation: 16441

You can use this.props.location from withRouter to get the current pathname. Use that to check against /home or whatever your home page is, and then you can add a class to the Header that changes the color.

Upvotes: 1

Alexei Darmin
Alexei Darmin

Reputation: 2129

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.

Upvotes: 5

Related Questions