Wednesday, October 5, 2022
HomeWeb DevelopmentUtilizing React Native Snackbar to create customized pop-up messages

Utilizing React Native Snackbar to create customized pop-up messages


Pop-up messages have turn out to be quite common on web sites. You should utilize these messages to show notifications or related info to your customers based mostly on the person’s interplay state — for instance, to point loading pages, getting requests, and so forth.

Snackbar is a software that may enable you obtain this characteristic in your React Native undertaking. Identical to toastify-react-native, react-native-toast-message, and different toast libraries, Snackbar helps you show notifications or pop-up messages in your React Native utility.

Moreover being the identify of this toast library, “snackbar” additionally refers to a particular kind of pop-up message that can be utilized to show info to customers. Snackbars animate into the viewport from the underside of the display and include an non-obligatory motion button for the person.

On this article, we are going to see find out how to use the React Native Snackbar bundle to create a very cool pop-up message or notification. We’ll see the options that Snackbar offers us and find out how to add and deal with button occasions with the bundle.

Leap forward:

Putting in Snackbar in your React Native undertaking

You should utilize both of the code instructions beneath to put in the bundle in your React Native utility:

// Npm
npm i react-native-snackbar

// Yarn
yarn add react-native-snackbar

Upon getting put in the bundle, you ought to be prepared to make use of Snackbar in your undertaking.

Utilizing Snackbar in your React Native utility

To make use of the Snackbar bundle, first import it on the high of your element in your React Native utility:

/* App.js */
import Snackbar from "react-native-snackbar"

You could run into the error just like the picture beneath or one thing comparable after importing the Snackbar library in your app:

Type Error Message Shown After Importing Snackbar Library

When you encounter this downside, create a folder referred to as _mocks_ within the root of your utility. Inside the folder, create a file referred to as react-native-snackbar.js and add the next code contained in the file:

/* react-native-snackbar.js */

module.exports = {
  present: jest.fn()
};

After that, clear your Gradle and construct to sync the adjustments:

cd android && ./gradlew clear

Within the above code, you’re shifting into your android folder, which is discovered inside your React Native folder. Then, ./gradlew clear makes use of your Gradle wrapper to scrub your undertaking by deleting your earlier construct listing, rebuilding it, and configuring your modules within the course of.

This solves the React Native downside above as a result of it syncs our new adjustments whereas it creates a brand new construct listing.

After constructing your undertaking and ensuring all the pieces works nice, you may merely name Snackbar in your element like so:

/* App.js */

Snackbar.present({
  textual content: 'Hiya world',
  period: Snackbar.LENGTH_SHORT,
});

Easy, proper? You too can add a button to your Snackbar and deal with your button occasion to verify the fitting factor occurs when your person touches the button — for instance, undoing a previous motion or closing the Snackbar.

See find out how to set this up within the code beneath and see the */ Do one thing. */ remark the place you may customise your button occasion:

/* App.js */

Snackbar.present({
  textual content: 'Hiya world',
  period: Snackbar.LENGTH_INDEFINITE,
  motion: {
    textual content: 'shut',
    textColor: 'inexperienced',
    onPress: () => { /* Do one thing. */ },
  },
});

Some toast libraries supply a number of notification variants. For instance, React-Toastify has toast variants reminiscent of success, error, and so forth. Snackbar doesn’t supply such a characteristic; it has just one notification variant.

However, you may at all times fashion your pop-up messages to suit no matter state, occasion, or info you wish to talk to your customers. Typically talking, the colour inexperienced tends to point a hit notification, whereas the colour pink is often used to indicate an error or warning message.


Extra nice articles from LogRocket:


Organising React Native Snackbar choices

Snackbar additionally has some choices reminiscent of textual content, period, variety of traces, and others that enable to you fashion and customise your notifications. We will probably be taking a look at what these choices are, together with the place and find out how to use them in our utility.

textual content possibility

The primary possibility is the textual content possibility. It permits you to specify what info you wish to move throughout to your person, reminiscent of success textual content or an error message.

/* Success */
Snackbar.present({
  textual content: 'Login profitable',
  period: Snackbar.LENGTH_SHORT,
});

/* Error */
Snackbar.present({
  textual content: 'Sorry, Incorrect login particulars',
  period: Snackbar.LENGTH_SHORT,
});

Within the code above, we created two Snackbars with completely different textual content choices: Login profitable and Sorry, Incorrect login particulars. The textual content possibility is at all times required since you’re the one setting what info you wish to move throughout.

period possibility

Your Snackbar’s period possibility specifies how lengthy you need your toast notification to be proven. Snackbar has offers three period choices: SHORT, LONG, and INDEFINITE.

  • Snackbar_LENGTH_SHORT runs for simply over a second
  • Snackbar_LENGTH_LONG runs for about three seconds
  • Snackbar_LENGTH_INDEFINITE stays on the display till it’s changed by one other Snackbar or dismissed by the person

By default, the period makes use of the Snackbar.LENGTH_SHORT possibility except you specify your required period explicitly.

Check out the code beneath to see find out how to implement every possibility:

/* Snackbar.LENGTH_SHORT */
Snackbar.present({
  textual content: 'Login profitable',
  period: Snackbar.LENGTH_SHORT,
});

/* Snackbar.LENGTH_LONG */
Snackbar.present({
  textual content: 'Login profitable',
  period: Snackbar.LENGTH_LONG,
});

/* Snackbar.LENGTH_INDEFINITE */
Snackbar.present({
  textual content: 'Login profitable',
  period: Snackbar.LENGTH_INDEFINITE,
});

numberOfLines possibility

The numberOfLines possibility specifies the variety of traces the Snackbar notification is allowed earlier than it may be truncated. For instance:

/* App.js */

Snackbar.present({
      textual content: 'Hiya toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldHello toast worldello toast world ',
      period: Snackbar.LENGTH_SHORT,
      numberOfLines: 2
    });

The above solely permits for 2 traces earlier than the remainder of the textual content is truncated. An ellipsis is used to indicate that the textual content has been lower off. You possibly can see the outcomes beneath:

Example Snackbar Message Shown In Grey Against Black App Background With Repeating "Hello Toast World" Message Shown Truncated After Two Lines; Truncation Is Indicated By Ellipse

The default variety of traces for this selection is 2 traces.

fontFamily, textColor, and backgroundColor choices

You may make your Snackbar extra custom-made in your React Native app by utilizing textColor, backgroundColor, and fontFamily choices.

  • textColor permits you to change the colour of the pop-up textual content
  • backgroundColor adjustments the background colour of the pop-up notification
  • fontFamily can be utilized to vary the font household to no matter you need

The default textColor is White, whereas the default backgroundColor is Darkgrey.

See the textColor and backgroundColor choices in motion beneath:

/* App.js */

    Snackbar.present({
      textual content: 'That is an Error message',
      period: Snackbar.LENGTH_SHORT,
      numberOfLines: 2,
      textColor: '#fff',
      backgroundColor: '#cc0000'
    });

Example Of Customizing Snackbar To Indicate Error Message Using Red Color

motion possibility

The motion possibility permits you to create an motion to be dealt with on the Snackbar. It exhibits together with the Snackbar and permits the person carry out an motion. An instance motion could possibly be closing or hiding the Snackbar after it opens.

You would possibly wish to move necessary info when the person masses a display or when the person clicks on a view or button. In such a state of affairs, you’d wish to hold displaying this info to the person till the person decides to cover or shut it manually.

You should utilize Snackbar.dismiss() to to take away or dismiss any obtainable or present notification, like so:

/* App.js */

Snackbar.present({
   textual content: 'Welcome to our Snackbar tutorial! Are you excited?',
   period: Snackbar.LENGTH_INDEFINITE,
   numberOfLines: 2,
   textColor: '#fff',
   backgroundColor: 'inexperienced',
   motion: {
     textual content: 'Conceal Pop-up',
     textColor: '#fff',
     onPress: () => {
        Snackbar.dismiss();
      }
   }
 });

Example Snackbar Welcome Message Shown In Green Against Black Background With Hide Pop Up Button At Right Side Of Snackbar

When you click on on the Conceal Pop-up motion button, it closes the Snackbar notification.

You too can create a unique button perform and name it in your Snackbar, like so:

/^ App.js */

  const closePopup = () => {
    Snackbar.dismiss();
  };

  const showToast = () => {
    Snackbar.present({
      textual content: 'Welcome to our Snackbar tutorial! Are you excited?',
      period: Snackbar.LENGTH_INDEFINITE,
      numberOfLines: 2,
      textColor: '#fff',
      backgroundColor: 'inexperienced',
      motion: {
        textual content: 'Shut Pop-up',
        textColor: '#fff',
        onPress: () => closePopup
      }
    });
  };

The above instance works similar to the opposite examples the place we referred to as our Snackbar.dismiss() inside our motion. Nevertheless, you may resolve to make use of a unique perform to forestall code ambiguity — i.e., make your code cleaner — as an alternative of getting a protracted perform inside one other lengthy perform.

One other frequent state of affairs for which the above instance can be utilized is one the place you might be calling completely different Snackbars. In such a state of affairs, you may select to have one closePopup perform and name it wherever you want it. See beneath instance for additional clarification:

/^ App.js */

  const closePopup = () => {
    /* you are able to do one thing right here earlier than closing the Snackbar */
    /* like opening a "Are you certain you wish to cancel" modal */
    Snackbar.dismiss();
  };

  const getRequest = () => {
    axios
      .get(api)
      .then((response) => {
        // console.log(response)

        Snackbar.present({
          textual content: "Request was profitable",
          period: Snackbar.LENGTH_INDEFINITE,
          numberOfLines: 2,
          textColor: "#fff",
          backgroundColor: "inexperienced",
          motion: {
            textual content: "Shut Pop-up",
            textColor: "#fff",
            onPress: () => closePopup
          }
        });
      })
      .catch((error) => {
        Snackbar.present({
          textual content: `Error message: ${error}`,
          period: Snackbar.LENGTH_INDEFINITE,
          textColor: "#fff",
          backgroundColor: "pink",
          motion: {
            textual content: "Shut Pop-up",
            textColor: "#fff",
            onPress: () => closePopup
          }
        });
      });
  };

Placing all of it collectively: Utilizing Snackbar in a easy React Native app

Now that we have now seen how the Snackbar library works, let’s put what we have now discovered collectively and construct a quite simple React Native utility with it. See the total code beneath, with a extra detailed clarification beneath the code block:

/* App.js */

import React, { useState, useEffect } from 'react';
import { SafeAreaView, StyleSheet, Textual content, useColorScheme, View, TouchableOpacity } from 'react-native';
import { Colours } from 'react-native/Libraries/NewAppScreen';
import Snackbar from 'react-native-snackbar';

const App = () => {
  const isDarkMode = useColorScheme() === 'darkish';
  const [ loadOptions, setLoadOptions ] = useState(false);
  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colours.darker : Colours.lighter
  };

  useEffect(() => {
    Snackbar.present({
      textual content: 'Welcome to our Snackbar tutorial! Are you excited?',
      period: Snackbar.LENGTH_INDEFINITE,
      textColor: isDarkMode ? Colours.lighter : Colours.darker,
      backgroundColor: isDarkMode,
      motion: {
        textual content: 'Shut Pop-up',
        textColor: '#fff',
        onPress: () => {
          Snackbar.dismiss();
        }
      }
    });
  }, []);

  const showOptions = () => {
    Snackbar.present({
      textual content: 'Loading SnackBar Choices...',
      period: Snackbar.LENGTH_SHORT,
      textColor: '#fff',
      backgroundColor: 'inexperienced'
    });
    setTimeout(() => {
      setLoadOptions(true);
    }, 2000);
  };

  return (
    <SafeAreaView fashion={[ backgroundStyle, styles.sectionContainer ]}>
      <View>
        <Textual content fashion={types.sectionTitle}> A SnackBar Tutorial </Textual content>
      </View>
      <TouchableOpacity onPress={showOptions} fashion={types.buttonHighlight}>
        <Textual content fashion={types.button}>Present Snackbar Choices</Textual content>
      </TouchableOpacity>
      {loadOptions && (
        <View>
          <Textual content fashion={types.sectionList}>1. Textual content</Textual content>
          <Textual content fashion={types.sectionList}>2. Length</Textual content>
          <Textual content fashion={types.sectionList}>3. Variety of Traces</Textual content>
          <Textual content fashion={types.sectionList}>4. Textual content Shade</Textual content>
          <Textual content fashion={types.sectionList}>5. Background Shade</Textual content>
          <Textual content fashion={types.sectionList}>6. Font household</Textual content>
          <Textual content fashion={types.sectionList}>7. Motion</Textual content>
        </View>
      )}
    </SafeAreaView>
  );
};

const types = StyleSheet.create({
  sectionContainer: {
    flex: 1,
    paddingHorizontal: 24,
    paddingTop: 24
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    marginBottom: 20
  },
  buttonHighlight: {
    marginVertical: 8,
    fontWeight: '400',
    backgroundColor: '#fff',
    padding: 5,
    borderRadius: 5
  },
  button: {
    fontSize: 24,
    colour: '#000',
    textAlign: 'heart',
    fontWeight: '700'
  },
  sectionList: {
    fontSize: 22,
    fontWeight: '600',
    marginBottom: 10
  }
});
export default App;

Within the above code, we’re displaying a Snackbar pop-up message to welcome the person as our web page masses. This message — Welcome to our Snackbar tutorial! Are you excited? — has an indefinite period, so it doesn’t depart till the person dismisses it.

Subsequent, on click on of the Present Snackbar Choices button, we name the second Snackbar, however this time we use a brief period to indicate the Loading SnackBar Choices... message to point to the person that their request is loading.

This second Snackbar then disappears simply earlier than the listing of choices masses on the web page, making the person expertise and interactivity good and funky.

See these Snackbars in motion beneath:

Example Simple Snackbar Tutorial React Native App Frontend Showing Two Snackbar Examples. First Snackbar Shows Welcome Message With Indefinite Duration And Close Pop Up Button. Second Snackbar Appears In Green After Show Snackbar Options Button Is Touched To Show Loading State And Disappears Just Before Snackbar Options Appear To User

Conclusion

We’ve seen how the Snackbar library works and find out how to use it. It’s fairly easy to make use of and appears actually cool in our utility, too.

Observe with the code examples above, and you’ll simply get a cling of utilizing Snackbar in React Native functions. This instance is simply to indicate find out how to use the Snackbar library to show customized pop-up messages. You possibly can go forward and use them anyplace you want in your app.

LogRocket: Immediately recreate points in your React Native apps.

LogRocket is a React Native monitoring answer that helps you reproduce points immediately, prioritize bugs, and perceive efficiency in your React Native apps.

LogRocket additionally helps you enhance conversion charges and product utilization by displaying you precisely how customers are interacting together with your app. LogRocket’s product analytics options floor the explanation why customers do not full a specific circulation or do not undertake a brand new characteristic.

Begin proactively monitoring your React Native apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments