Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Created December 29, 2017 00:24
Show Gist options
  • Save joshwcomeau/3047807c0d8d454d0236aaa7c75b478b to your computer and use it in GitHub Desktop.
Save joshwcomeau/3047807c0d8d454d0236aaa7c75b478b to your computer and use it in GitHub Desktop.
FitText port
// @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