I am trying to center a text input with a width that is the length of the text input. However when I use alignSelf: 'center', or alignItems: 'center', the text input is not visible without a width.
For example:
render() {
return <View style={{flex: 1}}>
<TextInput style={{alignSelf: 'center', minWidth: 1}}>
<View/>
}
Here the minWidth ensures that the textInput can be seen but it does not expand when you type in it. And without a width / minWidth the textInput would not be seen unless the centering style was removed.
Example with almost workable workaround:
constructor(props) {
super(props)
this.state = {
txt: ""
txtWidth: 0
}
}
render() {
return <View style={{flex: 1}}>
<TextInput
style={{minWidth: 1, alignSelf: 'center', width: this.state.txtWidth}}
value={this.state.txt}
onChange={txt=>this.setState({txt: txt.nativeEvent.text})}
/>
<Text
style={{position: 'absolute', right: 100000}}
onLayout={e=>this.setState({txtWidth:e.nativeEvent.layout.width})}
>
{this.state.txt}
</Text>
<View/>
}
As the text input receives input, it grows in size and works great. However, one thing prevents it from being full proof. The e.nativeEvent.layout.width value for emoji is always 20. And the actual width of the given emoji is not 20. Thus the txtWidth is no longer the correct width for the textInput and pieces of the textInput are now cut off.
Has anyone come up with a good solution for a centered text input with a dynamic width. I have been stumped on this for way too long. Would be happy to provide clarity if needed as well.
Thanks!