How to style a button in React Native?

Member

by beaulah , in category: JavaScript , a year ago

How to style a button in React Native?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by isadore , a year ago

@beaulah 

To style a button in React Native, you can use the StyleSheet API, which is similar to CSS.


Here is an example of how to style a button:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from 'react';
import { StyleSheet, TouchableOpacity, Text } from 'react-native';

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#2196F3',
    borderRadius: 10,
    padding: 10,
    margin: 10,
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

const CustomButton = ({ title, onPress }) => {
  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={styles.buttonText}>{title}</Text>
    </TouchableOpacity>
  );
};

export default CustomButton;


In this example, we are using the StyleSheet.create method to define our styles. We are defining the backgroundColor, borderRadius, padding, and margin for the button, as well as the color, fontSize, fontWeight, and textAlign for the text inside the button.


We are also using the TouchableOpacity component to make the button interactive. The onPress prop specifies the function to be called when the button is pressed.


You can then use this CustomButton component in your app like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import React from 'react';
import { View } from 'react-native';
import CustomButton from './CustomButton';

const App = () => {
  const handlePress = () => {
    console.log('Button pressed!');
  };

  return (
    <View>
      <CustomButton title="Press me" onPress={handlePress} />
    </View>
  );
};

export default App;


This will render a blue button with white text and the text "Press me" inside it. When the button is pressed, the handlePress function will be called and "Button pressed!" will be logged to the console.

Member

by sister , 4 months ago

@beaulah 

To style a button in React Native, you can use the StyleSheet API, which is similar to CSS. Below is an example of how to style a button in React Native:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from 'react';
import { StyleSheet, TouchableOpacity, Text } from 'react-native';

const styles = StyleSheet.create({
  button: {
    backgroundColor: '#2196F3',
    borderRadius: 10,
    padding: 10,
    margin: 10,
  },
  buttonText: {
    color: 'white',
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

const CustomButton = ({ title, onPress }) => {
  return (
    <TouchableOpacity onPress={onPress} style={styles.button}>
      <Text style={styles.buttonText}>{title}</Text>
    </TouchableOpacity>
  );
};

export default CustomButton;