Skip to content

Instantly share code, notes, and snippets.

@jrichardlai
Created April 1, 2016 03:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrichardlai/de17535abc02a7472d7f4c17911087fd to your computer and use it in GitHub Desktop.
Save jrichardlai/de17535abc02a7472d7f4c17911087fd to your computer and use it in GitHub Desktop.
AutoScaleText for React Native
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