Created
December 29, 2017 00:24
-
-
Save joshwcomeau/3047807c0d8d454d0236aaa7c75b478b to your computer and use it in GitHub Desktop.
FitText port
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
// @flow | |
// Reimplementation of the jQuery plugin "FitText" | |
// https://github.com/davatron5000/FitText.js/blob/master/jquery.fittext.js | |
import React, { PureComponent } from 'react'; | |
type Props = { | |
compressor: number, | |
children: React$Node, | |
}; | |
class FitText extends PureComponent<Props> { | |
static defaultProps = { | |
compressor: 1, | |
}; | |
elem: ?HTMLElement; | |
componentDidMount() { | |
this.resize(); | |
window.addEventListener('resize', this.resize); | |
} | |
componentDidUpdate() { | |
this.resize(); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.resize); | |
} | |
resize = () => { | |
const { compressor } = this.props; | |
const { elem } = this; | |
if (!elem) { | |
return; | |
} | |
const { width } = elem.getBoundingClientRect(); | |
elem.style.fontSize = width / (compressor * 10) + 'px'; | |
}; | |
render() { | |
const { children } = this.props; | |
// prettier-ignore | |
return ( | |
<div ref={(elem: ?HTMLElement) => (this.elem = elem)}> | |
{children} | |
</div> | |
); | |
} | |
} | |
export default FitText; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment