React Native – How To Create Custom Buttons In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, We will learn about how to create custom buttons in React Native. React Native is an excellent framework for building native mobile applications. It allows us to build apps that will work on both iOS and Android platforms. Core UI components such as <Button /> look different on each platform, and there are limited styling and customization options. For this and many other reasons, it’s critical to know how to create buttons that look consistent regardless of the operating system. In this article, we’ll walk through how to create various types of custom buttons in React Native.

A famous quote about learning is :

” Tell me and I forget, teach me and I may remember, involve me and I learn.”

How To Create Custom Buttons In React Native ?

So Let’s begin.


Create Button Using Stylesheet

A basic button component that should render nicely on any platform. Supports a minimal level of customization.

For Example – App.js

import React from "react";
import { View, Button, StyleSheet } from "react-native";

const App = () => {
  return (
    <View style={styles.screenContainer}>
      <Button title="Press Button" />
    </View>
  );
};

const styles = StyleSheet.create({
  screenContainer: {
    flex: 1,
    justifyContent: "center",
    padding: 16
  }
});

export default App;

In the above code block, a core <Button /> component is declared and wrapped inside a container. StyleSheet, is an API provided by the React Native framework as an abstraction to CSS StyleSheets.


The Custom Button Component

Now that we’ve set up the main screen, it’s time to turn our attention to the custom button component.

const AppButton = props => (
    // ...
)

Name the custom button component AppButton.

Import the <TouchableOpacity /> and <Text /> components from react-native. To create custom buttons, we need to customize the <TouchableOpacity /> component and include the <Text /> component inside of it to display the button text. Next, create the StyleSheet properties to style the button.

<TouchableOpacity />, as the name suggests, is a touchable component, which means it can respond to the user’s touch. When we press the button, the opacity decreases. We can control the opacity by passing an activeOpacity prop to the <TouchableOpacity /> component.

If we want to change the opacity for all the custom buttons in our app, use the defaultProps property. defaultProps is a property in a React component that sets default values for the prop argument.

After we’ve imported TouchableOpacity, The onPress props expect a function or a function reference that will execute when the user presses the button. The full code for this section is as follows.

For Example App.js

import React from "react";
import { View, Button, StyleSheet, TouchableOpacity, Text } from "react-native";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const AppButton = ({ onPress, title }) => (
  <TouchableOpacity onPress={onPress} style={styles.appButtonContainer}>
    <Text style={styles.appButtonText}>{title}</Text>
  </TouchableOpacity>
);

const App = () => {
  return (
    <View style={styles.screenContainer}>
      <AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />
    </View>
  );
};

const styles = StyleSheet.create({
  screenContainer: {
    flex: 1,
    justifyContent: "center",
    padding: 16
  },
  appButtonContainer: {
    elevation: 8,
    backgroundColor: "#009688",
    borderRadius: 10,
    paddingVertical: 10,
    paddingHorizontal: 12
  },
  appButtonText: {
    fontSize: 18,
    color: "#fff",
    fontWeight: "bold",
    alignSelf: "center",
    textTransform: "uppercase"
  }
});

export default App;

The custom button should look like this:

Custom Button Component Output
Custom Button Component Output


Adding More Props In Custom Button Component

Since it’s a custom button component, we have the liberty of piling on additional props. For example, we can add a prop to change the button size or change the background color.

const AppButton = ({ onPress, title, size, backgroundColor }) => (
  <TouchableOpacity
    onPress={onPress}
    style={[
      styles.appButtonContainer,
      size === "sm" && {
        paddingHorizontal: 8,
        paddingVertical: 6,
        elevation: 6
      },
      backgroundColor && { backgroundColor }
    ]}
  >
    <Text style={[styles.appButtonText, size === "sm" && { fontSize: 14 }]}>
      {title}
    </Text>
  </TouchableOpacity>
);

// ...
<AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />;

We’ll see the following result on our screen.

Custom Button Additional Props Output
Custom Button Additional Props Output


Styling the button using Linear gradient background

By default, React Native doesn’t have an API to create a linear gradient background in a container. Luckily, there’s another expo utility library for React Native that we can use to create linear gradient colors.

We need to create project and import the <LinearGradient /> component from the expo-linear-gradient library. we ‘ll need to make some adjustments in the <AppButton /> component. Wrap the <TouchableOpacity /> component around the <LinearGradient /> component and add the style prop to the <LinearGradient /> component. The colors prop in LinearGradient accepts an array, which contains the color values that will be used to create the linear gradient.

The full code for this section is as below:

For Example – App.js

import React from "react";
import { View, StyleSheet, TouchableOpacity, Text } from "react-native";
import { LinearGradient } from "expo-linear-gradient";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const AppButton = ({ onPress, title }) => (
    <TouchableOpacity onPress={onPress}>
        <LinearGradient
            colors={["#004d40", "#009688"]}
            style={styles.appButtonContainer}
        >
            <Text style={styles.appButtonText}>{title}</Text>
        </LinearGradient>
    </TouchableOpacity>
);

const App = () => {
    return (
        <View style={styles.screenContainer}>
            <AppButton title="Hey there!" size="sm" backgroundColor="#007bff" />
        </View>
    );
};

const styles = StyleSheet.create({
    screenContainer: {
        flex: 1,
        justifyContent: "center",
        padding: 16
    },
    appButtonContainer: {
        elevation: 8,
        backgroundColor: "#009688",
        borderRadius: 10,
        paddingVertical: 10,
        paddingHorizontal: 12
    },
    appButtonText: {
        fontSize: 18,
        color: "#fff",
        fontWeight: "bold",
        alignSelf: "center",
        textTransform: "uppercase"
    }
});

export default App;

We’ll see the following result on our screen.

Custom Button Gradient Background Output
Custom Button Gradient Background Output


Controlling button styles using state

As in any React application, we can add styles to our component based on the current value of the state. For example, if we want to disable a button for a certain period of time after it’s pressed, the button must have a disabled background color so that the user knows it’s temporarily inactive.

Add a style property inside the StyleSheet object to represent the disabled color. For this example,  we’ll use black.

const styles = StyleSheet.create({
  // ...
  appButtonDisabled: {
    backgroundColor: "#000"
  }
});

Next, refactor the <AppButton /> component and use the useState hook to change the disabled state.

const AppButton = ({ title }) => {
  const [isDisabled, setDisabled] = useState(false);

  const handlePress = () => {
    setDisabled(true);
    setTimeout(() => setDisabled(false), 3000);
  };

  return (
    <TouchableOpacity
      onPress={handlePress}
      style={[
        styles.appButtonContainer,
        isDisabled && styles.appButtonDisabled
      ]}
      disabled={isDisabled}
    >
      <Text style={styles.appButtonText}>{title}</Text>
    </TouchableOpacity>
  );
};

We can pass a disabled prop to the TouchableOpactiy component to disable the onPress behavior. We can pass an array of style objects to the style prop. So when isDisabled is set to true, we can add the appButtonDisabled property to the style prop array using the && operator.


Styling the button using styled-components

styled-component is a CSS-in-JS library that enables us to write each component with its own style and encapsulate the code in a single location.

React Native follows a certain specification for styling these components. For example, all CSS property names must be written in camelCase — background-color should be specified as backgroundColorborder-width as borderWidth, etc.

This can be a little disorienting for a developer who is approaching mobile app development from a web development background. The styled-components library enables us to write native CSS for styling a React Native component. Under the hood, styled-components simply converts the CSS text into a React Native StyleSheet object.

 We need to install styled-components using npm or yarn package manager. Replace the TouchableOpacity and Text components with ButtonContainer and ButtonText, respectively. These new components will be created using the syntax from styled-components.

const AppButton = ({ onPress, title }) => (
  <ButtonContainer onPress={onPress}>
    <ButtonText>{title}</ButtonText>
  </ButtonContainer>
);

styled-components uses tagged template literals to style the components using backticks (`). Each styled component must have a React Native component attached to it.

const ButtonContainer = styled.TouchableOpacity``;

const ButtonText = styled.Text``;

Inside the backticks, add CSS rules.

const ButtonContainer = styled.TouchableOpacity`
  elevation: 8;
  border-radius: 10px;
  padding-vertical: 10px;
  padding-horizontal: 12px;
  background-color: #951754;
`;

const ButtonText = styled.Text`
  font-size: 18;
  color: #fff;
  font-weight: bold;
  align-self: center;
  text-transform: uppercase;
`;

Putting everything together, our code should look like this:

import React, { useState } from "react";
import { View, StyleSheet, TouchableOpacity, Text } from "react-native";
import styled from "styled-components";

TouchableOpacity.defaultProps = { activeOpacity: 0.8 };

const ScreenContainer = styled.View`
    flex: 1;
    justify-content: center;
    padding: 16px;
`;

const ButtonContainer = styled.TouchableOpacity`
  elevation: 8;
  border-radius: 10px;
  padding-vertical: 10px;
  padding-horizontal: 12px;
  background-color: #951754;
`;

const ButtonText = styled.Text`
  font-size: 18px;
  color: #fff;
  font-weight: bold;
  align-self: center;
  text-transform: uppercase;
`;

const AppButton = ({ onPress, title }) => (
  <ButtonContainer onPress={onPress}>
    <ButtonText>{title}</ButtonText>
  </ButtonContainer>
);

const App = () => {
  return (
    <ScreenContainer>
      <AppButton title="Hey there!" size="sm" />
    </ScreenContainer>
  );
};

export default App;

That’s all about in this article.


Conclusion

In this article, We understood that how to create various types of custom buttons in React Native. As a developer, we must build UI components to match whatever reference or design our design team comes up with. We must make the UI components look precisely as they’re outlined in our client’s plan or prototype.

Thanks for reading ! I hope you enjoyed and learned about creating Custom Buttons in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!😊😊😊

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s