Created
February 24, 2019 21:33
-
-
Save johnpolacek/4dbfbf231ca267abc834046fa118149a to your computer and use it in GitHub Desktop.
React component for controlling widows for responsive line breaks in your text
This file contains hidden or 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 PropTypes from 'prop-types' | |
import React from 'react' | |
class ResponsiveWidows extends React.Component { | |
constructor() { | |
super() | |
this.state = {} | |
} | |
componentDidMount() { | |
let numWidows = 0 | |
if (typeof(this.props.widows) == 'object') { | |
const width = window.innerWidth | |
for (let i=0; i<this.props.breakpoints.length; i++) { | |
if (this.props.breakpoints[i] >= width) { | |
numWidows = i == 0 ? this.props.widows[0] : this.props.widows[i-1] | |
break; | |
} | |
} | |
numWidows = numWidows === 0 ? this.props.widows[this.props.widows.length-1] : numWidows | |
} else { | |
numWidows = this.props.widows || 1 | |
} | |
this.setState({widows:numWidows}) | |
console.log(this.props.widows[0]) | |
console.log('numWidows',numWidows) | |
} | |
render() { | |
const words = this.props.children.split(' ') | |
return <>{words.map((word, i) => word + (i > words.length-(this.state.widows+1) ? '\u00a0' : ' ')).join('')}</> | |
} | |
} | |
ResponsiveWidows.propTypes = { | |
children: PropTypes.string.isRequired, | |
widows: PropTypes.oneOfType([ | |
PropTypes.number, | |
PropTypes.arrayOf(PropTypes.number), | |
]).isRequired, | |
breakpoints: PropTypes.arrayOf(PropTypes.number) | |
} | |
export default ResponsiveWidows |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment