Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fadookie/c71edcfe1e595f5cab374d4297ba1e02 to your computer and use it in GitHub Desktop.
Save fadookie/c71edcfe1e595f5cab374d4297ba1e02 to your computer and use it in GitHub Desktop.
Auto-resizing text in pure js for react native, updated for RN 0.40
'use strict';
import React, { Component } from 'react';
import { findNodeHandle, StyleSheet, Text, View, NativeModules } from 'react-native';
const UIManager = NativeModules.UIManager;
class AutoresizeText extends Component {
constructor(props) {
super(props);
this.state = {
size: 0.5,
}
}
tryNewSize() {
requestAnimationFrame(() => {
UIManager.measureLayoutRelativeToParent(
findNodeHandle(this._text),
() => { React.AlertIOS.alert('ERROR!') },
(x, y, w, h) => { this.isSizeOk(w, h) },
);
});
}
isSizeOk(w, h) {
if (h > this.props.height) {
if (this.state.size == 0.5) {
this.setState({complete: true});
} else {
this.setState({size: this.state.size -= 0.5, complete: true});
requestAnimationFrame(() => {
this.tryNewSize();
});
}
} else {
if (!this.state.complete) {
this.setState({size: this.state.size += 0.5});
requestAnimationFrame(() => {
this.tryNewSize();
});
}
}
}
_onLayout() {
// console.log(arguments);
}
componentDidMount() {
// Convert this to async/await function so I can process synchronously in loop
this.tryNewSize();
}
render() {
return (
<Text ref={component => this._text = component}
onLayout={this._onLayout}
style={{backgroundColor: 'transparent', fontSize: this.state.size, color: this.state.complete ? 'black': 'transparent'}}>
{this.props.children}
</Text>
)
}
}
class AutoresizeTextExample extends Component {
render() {
return (
<View style={styles.container}>
<View style={{width: 400, height: 300, borderWidth: 1, borderColor: 'red', overflow: 'hidden'}}>
<AutoresizeText width={400} height={300}>
Carles umami Echo Park, drinking vinegar disrupt four dollar toast
vinyl. Forage chia butcher, fap American Apparel selvage
Kickstarter retro cred. Pinterest raw denim wayfarers heirloom
flexitarian chia. Umami 8-bit pug, ugh actually hashtag
Intelligentsia food truck irony sartorial post-ironic disrupt
squid. Fap swag fixie try-hard pug blog Carles, authentic Odd
Future PBR&B hashtag butcher cardigan food truck wolf. Salvia
seitan gastropub Shoreditch disrupt, lo-fi chillwave drinking
vinegar narwhal post-ironic meh ennui selvage four loko whatever.
</AutoresizeText>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AutoresizeTextExample', () => AutoresizeTextExample);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment