Skip to content

Instantly share code, notes, and snippets.

@Xananax
Created February 11, 2018 11:34
Show Gist options
  • Save Xananax/7e8cf0b229d034190b5fa377857f99ab to your computer and use it in GitHub Desktop.
Save Xananax/7e8cf0b229d034190b5fa377857f99ab to your computer and use it in GitHub Desktop.
React Element for fitty.js
declare module 'fitty'{
export interface Options
{ minSize: number
; maxSize: number
; multiLine: boolean
; observeMutations:
{ subtree?: boolean
; childList?: boolean
; characterData?: boolean
}
}
export interface Fitted
{ fit: () => void
; unsubscribe: () => void
; element: HTMLElement
}
export interface Fitty
{ ( el: string | HTMLElement , opts?: Partial<Options> ): Fitted
; observeWindow: boolean
; observeWindowDelay: number
; fitAll: () => void
}
export const fitty:Fitty
export default fitty
}
import { TextFit } from './TextFit'
import * as React from 'react'
import { render } from 'react-dom'
const App = () =>
<div style={{width:300,height:300,background:'teal',float:'left'}}>
<TextFit>blah blah blah</TextFit>
</div>
render(<App/>,document.getElementById('root'))
import * as React from 'react'
import { Component } from 'react'
import fitty, { Options, Fitted } from 'fitty'
export type Props = Partial<Options> & {text?:string} & React.AllHTMLAttributes<HTMLSpanElement>
export const style =
{ display: `inline-block`
, whiteSpace: `nowrap`
}
export class TextFit extends Component<Props>
{ element:HTMLElement
; thing:Fitted
; fitted: boolean = false
; initialized: boolean = false
; componentDidMount()
{ this.fit()
}
; componentDidUpdate()
{ this.fit()
}
; componentWillReceiveProps(nextProps:Props)
{ if
( nextProps.children !== this.props.children
|| nextProps.minSize !== this.props.minSize
|| nextProps.maxSize !== this.props.maxSize
|| nextProps.multiLine !== this.props.multiLine
)
{ this.fitted = false
}
}
; componentWillUnmount()
{ this.thing.unsubscribe()
}
; fit()
{ if(this.fitted)
{ return
}
; if(!this.initialized)
{ this.thing = fitty(this.element)
}
else
{ this.thing.fit()
}
; this.fitted = true
; this.initialized = true
}
; makeRef =
(el:HTMLElement) =>
{ this.element = el
}
; render()
{ const { makeRef: ref } = this
; const
{ children, text, ...rest } = this.props
const props = { style, ref }
return (
<div {...rest}>
<span {...props}>{text}{children}</span>
</div>
)
}
}
@ilomon10
Copy link

ilomon10 commented Mar 7, 2020

Size not updating when container resize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment