react native button

React Native Button

React Native Button is a component that allows users to interact with the application by pressing it. Buttons can be customized with different colors, shapes, and sizes to fit the design of the application. It is one of the most commonly used components in React Native.

Creating a Button Component

To create a button component in React Native, we can use the TouchableHighlight or TouchableOpacity component provided by React Native.

TouchableHighlight: This component provides a simple feedback mechanism when the button is pressed. When the button is pressed, the background color of the button changes, and when it is released, it goes back to its original color.


<TouchableHighlight
  style={{ backgroundColor: "blue" }}
  onPress={() => console.log("Button Pressed")}
>
  <Text style={{ color: "white" }}>Press Me</Text>
</TouchableHighlight>

TouchableOpacity: This component provides a more subtle feedback mechanism when the button is pressed. When the button is pressed, the opacity of the button decreases slightly, and when it is released, it goes back to its original opacity.


<TouchableOpacity
  style={{ backgroundColor: "blue" }}
  onPress={() => console.log("Button Pressed")}
>
  <Text style={{ color: "white" }}>Press Me</Text>
</TouchableOpacity>

Passing Props to Button Component

The button component can be customized by passing props to it.

  • onPress: This prop is used to define the function to be executed when the button is pressed.
  • style: This prop is used to define the style of the button.
  • disabled: This prop is used to disable the button.
  • title: This prop is used to define the text displayed on the button.
  • accessibilityLabel: This prop is used to help users with disabilities to understand what the button does.

<TouchableOpacity
  style={{ backgroundColor: "blue" }}
  onPress={() => console.log("Button Pressed")}
  disabled={false}
  title="Press Me"
  accessibilityLabel="Press Me Button"
>
  <Text style={{ color: "white" }}>Press Me</Text>
</TouchableOpacity>

Conclusion

React Native Button is an essential component that is used in almost every application. By using the above examples, we can create customized buttons that match the design of our application. We can also pass props to the button component to define its behavior and accessibility.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe