React Native align icon left and text centered

Franch picture Franch · May 22, 2018 · Viewed 8.9k times · Source

I'm farily new to React Native, and I'm trying to do something very simple:

I want to create the following component:

A TouchableHighlight that has an image aligned to its left and text centered relative to the Touchable.

I've tried a bunch of options like adding padding or margin to the text but that just makes the button bigger and doesn't seem to be cleanest approach.

Here's what I've got so far:

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <View style={styles.appContainer}>
        <TouchableHighlight onPress={() => {}} style={styles.button}>
          <View style={styles.btnContainer}>
            <Image source={require('./assets/ic_logout.png')} style={styles.icon} />
            <Text style={styles.btnText}>Log out</Text>
          </View>
        </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  appContainer: {
    flex: 1,
    backgroundColor: 'lightgreen',
    alignItems: 'center',
    justifyContent: 'center'
  },
  btnContainer: {
    backgroundColor: '#1d2aba',
    paddingHorizontal: 60,
    paddingVertical: 10,
    flexDirection: 'row',
    alignItems: 'center',
    borderRadius: 5
  },
  button: {
    borderRadius: 5
  },
  icon: {
    transform: [{ rotate: '180deg'}],
    width: 25,
    height: 25
  },
  btnText: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    color: 'white'
  }
});

export default App;


For visual purposes:

React Native

Here's the Snack for your testing desires!
PS: Already tried this but to no avail.

Answer

Nirmalsinh Rathod picture Nirmalsinh Rathod · May 22, 2018

Here is you solution. Update the below style:

For icon:

icon: {
    transform: [{ rotate: '180deg'}],
    width: 25,
    height: 25,
    position: 'absolute',
    left: 2, // Keep some space between your left border and Image
  },

For Text:

 btnText: {
    textAlign: 'center',
    fontWeight: 'bold',
    fontSize: 16,
    color: 'white',
    height:'100%',
    width:'100%'
  }

You can update both style in your code and check.