-
-
Save jrichardlai/de17535abc02a7472d7f4c17911087fd to your computer and use it in GitHub Desktop.
AutoScaleText for React Native
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
import React from 'react-native'; | |
const { | |
NativeModules, | |
Text, | |
} = React; | |
const UIManager = NativeModules.UIManager; | |
class AutoScaleText extends React.Component { | |
static propTypes = { | |
...React.Text.propTypes, | |
maxFontSize: React.PropTypes.number.isRequired, | |
maxHeight: React.PropTypes.number.isRequired, | |
color: React.PropTypes.string, | |
style: React.PropTypes.oneOfType([ | |
React.PropTypes.number, | |
React.PropTypes.shape({ | |
width: React.PropTypes.number, | |
}), | |
]).isRequired, | |
}; | |
static defaultProps = { | |
color: 'black', | |
}; | |
constructor(props) { | |
super(props); | |
this.state = { | |
fontSize: props.maxFontSize, | |
finished: false, | |
}; | |
} | |
determineFontSize = () => { | |
UIManager.measure(React.findNodeHandle(this.refs.textView), (x, y, w, h, px, py) => { | |
if (h > this.props.maxHeight) { | |
this.setState({ | |
fontSize: this.state.fontSize - 0.5, | |
}); | |
this.determineFontSize(); | |
} | |
else { | |
this.setState({finished: true}); | |
} | |
}); | |
}; | |
render() { | |
return ( | |
<Text | |
ref='textView' | |
onLayout={this.determineFontSize} | |
{...this.props} | |
style={[ | |
this.props.style, | |
{ | |
fontSize: this.state.fontSize, | |
color: this.state.finished ? this.props.color : 'transparent', | |
}, | |
]} | |
> | |
{this.props.children} | |
</Text> | |
); | |
} | |
} | |
export default AutoScaleText; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment