Skip to content

Instantly share code, notes, and snippets.

@petertenhoor
Created March 11, 2020 09:37
Show Gist options
  • Save petertenhoor/9d598878ea0b9519d69f7e22de82ad6c to your computer and use it in GitHub Desktop.
Save petertenhoor/9d598878ea0b9519d69f7e22de82ad6c to your computer and use it in GitHub Desktop.
Fitty implementation in React
import fitty from "fitty"
import PropTypes from "prop-types"
import Parser from "html-react-parser"
import {PureComponent} from "react"
class FitText extends PureComponent {
/**
* Define default value for reference element
*/
$element = null
/**
* Define default value for fittyInstance
*/
fittyInstance = null
/**
* ComponentDidMount lifecycle
*/
componentDidMount() {
if (process.browser && this.$element !== null) {
//set throttle delay to 250ms
fitty.observeWindowDelay = 250
//create fitty instance
this.fittyInstance = fitty(this.$element, {minSize: 17, maxSize: 145})
}
}
/**
* componentWillUnmount lifecycle
*/
componentWillUnmount() {
if (this.fittyInstance !== null && this.$element !== null) this.fittyInstance.unsubscribe()
}
/**
* Render lifcycle
* @return {*}
*/
render() {
const {text} = this.props
//bail if no text
if (text === '') return null
return (
<span ref={($element) => this.$element = $element}>
{Parser(text)}
</span>
)
}
}
FitText.defaultProps = {
text: ''
}
FitText.propTypes = {
text: PropTypes.string
}
export default FitText
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment