Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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