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.
Add a comment
|
2 Answers
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.
2 Comments
Jschriemer
This answer makes sense, however, when I try it myself I receive the typeError: cannot read property 'location' of undefined. Any tips?
Alexei Darmin
@Jschriemer location should be read from
this.props so first confirm you're doing this within a correctly configured React Component. If that's not the issue, I'd check to make sure withRouter still exposes a location value (and has not deprecated it since my initial answer).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.
1 Comment
thomasna82
thanks for your help. Alexei Darmin just made it click with me.