Created
March 26, 2018 16:15
-
-
Save deanshub/5bb5893aba869767ebfbd5ef393f3b93 to your computer and use it in GitHub Desktop.
Controlling css classes of body element with react
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React,{Component} from 'react' | |
import PropTypes from 'prop-types' | |
export default class BodyClassName extends Component { | |
static propTypes = { | |
className: PropTypes.string, | |
} | |
static defaultProps = { | |
className: '', | |
} | |
componentDidMount() { | |
this.props.className.split(' ').forEach(className=>{ | |
document.body.classList.toggle(className, true) | |
}) | |
} | |
componentWillReceiveProps(nextProps) { | |
const currentClasses = this.props.className.split(' ') | |
const futureClasses = nextProps.className.split(' ') | |
const removeClasses = currentClasses.filter(className=>!futureClasses.includes(className)) | |
const addClasses = futureClasses.filter(className=>!currentClasses.includes(className)) | |
removeClasses.forEach(className=>{ | |
document.body.classList.toggle(className, false) | |
}) | |
addClasses.forEach(className=>{ | |
document.body.classList.toggle(className, true) | |
}) | |
} | |
componentWillUnmount() { | |
this.props.className.split(' ').forEach(className=>{ | |
document.body.classList.remove(className) | |
}) | |
} | |
render() { | |
return this.props.children | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment