React Native Button: Fit to text layout

2k views Asked by At

In the Button docs from React-Native here it shows an image which says: Fit to text layout. That is what I am searching for because my button always has full width, but I want it to only be as wide as the text is. But neither in the docs nor in the button code here I can find something related to that a prop or how can it achieve. Somebody has an idea how to get it?

2

There are 2 answers

0
Hugo Laplace On

I suggest making your own button with TouchableOpacity and Text.

For example this is my component I often use :

export default class RoundedButton extends React.Component<Props>{

  render(){
    const defStyles : StyleProp<ViewStyle> = [style.button, {
      backgroundColor: this.props.backgroundColor,
    }, this.props.style];
    if(this.props.shadow)
      defStyles.push(style.shadow);


    return(
      <TouchableOpacity
        disabled={!this.props.onPress}
        onPress={() => {
          if(this.props.onPress)
            this.props.onPress();
        }}
        style={defStyles}
      >
        <Text style={{
          color: this.props.textColor,
          fontFamily: fonts.bold,
          fontSize: 16
        }}>{this.props.centerText}</Text>

      </TouchableOpacity>
    );
  }

}

You can found the full gist here if you want : https://gist.github.com/Sangrene/176c1b87ad5b355e26b5c6aa80b96eae.

0
Mateus Marinho On

You can pass the prop adjustsFontSizeToFit={true} in your Text component.

If you add a fontSize in the styles of the Text, it will override this prop and won't work.

Example

<View style={{widht: 100, height: 60}}>
   <Text adjustsFontSizeToFit={true}>
     Your Text Here
   </Text>
</View>