12

I'm using TouchableOpacity to make a button as I'm learning react-native.

But the problem is, TouchableOpacity takes 100% width of the screen. But, I want to take the size/grow with the component present inside it.

How can I do it?

import React, { Component } from "react";
import { Text, TouchableOpacity } from "react-native";
export default class App extends Component {
    render(){
        return(
        <TouchableOpacity
            onPress={() => console.log("Pressed!")}
            style={{ backgroundColor: "red" }}
        >

            <Text>Press me!</Text>

        </TouchableOpacity>
        );
    }

When I decrease the width of the TouchableOpacity like 10 or 20, it automatically increases its height to fit the Text.

So, it possible for TouchableOpacity to grow with the size of component present inside it?

ssh
  • 491
  • 1
  • 8
  • 19
  • 3
    With your current code snipper, the TouchableOpacity should already wrap around the Text and grow with it in size. Are you sure you aren't setting `flex : 1` on a parent component? – patngo Apr 09 '18 at 03:07
  • @patngo My bad. Indeed I'm using `flex: 1` in `TouchableOpacity`. I thought I deleted the `style` prop but I missed it. Thanks for pointing out. Now it works. – ssh Apr 09 '18 at 03:40
  • 1
    FWIW I've added "flex: 0" to the TouchableOpacity's style directly and still having this problem, in case anybody has any ideas... – owencm Oct 01 '21 at 00:26

1 Answers1

13

You can actually use alignSelf: 'flex-start' or 'flex-end' depending on which side you want to pin

The1993
  • 592
  • 1
  • 7
  • 22