Saturday, November 26, 2022
HomeWeb DevelopmentConstruct a customized flashbar in React Native

Construct a customized flashbar in React Native


Cell app builders use totally different methods to inform customers about each foreground and background app occasions. For foreground app occasion alerts, builders sometimes use flashbars, conventional alert packing containers, toast messages, in-app notification programs, or some mixture of those. Native, platform-dependent push notifications are sometimes used for informing customers about background app occasions.

A flashbar is a contemporary, animated GUI ingredient that renders light-weight particulars about an app occasion. Flashbars sometimes seem in a nook of the display screen (in most situations, they seem on the highest or backside nook) and disappear after a pre-defined timeout. From the UI/UX perspective, flashbars are appropriate for many situations the place we have to notify the consumer concerning the app occasions’ statuses. For instance, you’ll be able to show the particular motion standing after inserting a brand new document right into a database.

React Native builders can use the favored react-native-flash-message library to show flashbars. On this article, I’ll clarify tips on how to construct and customise flashbar elements in React Native based on sensible necessities.

Soar forward:

Highlighted options of react-native-flash-message

The react-native-flash-message library enables you to add Materials Snackbar-like, low-priority alerting elements, and permits you to create flashbars based on gadget orientation and standing bar top, so it really works nicely on units with a notch (i.e., iPhone X).

I’ve highlighted some extra options under:

Cross-platform assist

This library gives a JavaScript-based resolution. In different phrases, it makes use of inbuilt React Native primitive elements like View, Textual content, and Picture with out utilizing customized native modules. So, you’ll be able to anticipate a constant flashbar feel and look throughout Android and iOS platforms. Additionally, this library gives a approach to management operating-system-level UI parts, such because the standing bar.

Customizability and extendability

This library gives varied self-explanatory props to customise the flashbar colours, icons, kinds, content material, and transition animations. So, you’ll be able to simply create a customized flashbar that matches your app theme in document time.

This package deal can also be versatile sufficient to allow you to lengthen it for any superior necessities, like creating your individual flashbar part.

Adherence to UI/UX ideas

You don’t have to set many props by your self to create a flashbar in your app. The react-native-flash-message library enables you to create a flashbar message with a message string by setting UX-friendly defaults. For instance, this library renders a grey flashbar on prime of the display screen and hides it after about two seconds by default.

Construct a React Native flashbar

We’ll create a brand new React Native app and add customized flashbars to grasp the options of the react-native-flash-message library. If it is advisable add flashbars to your current React Native app, you may also use the upcoming code examples with out creating a brand new mission.

Mission setup and configuration

If you happen to plan to create a brand new React Native mission for this tutorial, create one with the official React Native CLI:

npx react-native init CustomFlashbars
cd CustomFlashbars

As soon as the above command completes, run the newly created mission to ensure that every thing works:

npx react-native run-android
# --- or ---
npx react-native run-ios

Subsequent, set up react-native-flash-message as follows:

npm set up react-native-flash-message
# --- or ---
yarn add react-native-flash-message

Now, with a profitable set up, we will begin creating flashbars. Let’s present a primary flashbar first!

Making a primary flashbar

Add the next code to your App.js to show a primary flashbar:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  Button,
} from 'react-native';
import FlashMessage, { showMessage } from 'react-native-flash-message';

perform App() {
  perform handlePress() {
    showMessage({
      message: 'Hiya flashbars!'
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}/>
      <FlashMessage/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  }
});

export default App;

Right here, we show a flashbar with the default configuration by sending solely the message choice. As proven within the above code, we have to add the FlashMessage part as a worldwide part throughout the App part earlier than utilizing the showMessage perform.

When you add the worldwide FlashMessage part, you’ll be able to name the showMessage perform from wherever to indicate a flashbar message.

Run the above code and it is best to see a flashbar with a grey background, as proven within the following preview:

Basic gray flashbar.

The flashbar will disappear after 1850 milliseconds by default, however you customise that point allotment through the period choice within the message object. For instance, the next code hides the flashbar part after 5 seconds:

perform handlePress() {
  showMessage({
    message: 'Hiya flashbars!',
    period: 5000
  });
}

You need to use these message object choices within the world FlashMessage part, too:

<FlashMessage period={5000}/>

We sometimes present an alert title and outline inside UX-friendly packing containers to create constant, minimal, and versatile consumer interfaces. We will do the identical with flashbar messages.

The next code snippet reveals the flashbar title and outline within the flashbar and renders a multi-line flashbar message:

perform handlePress() {
  showMessage({
    message: 'react-native-flash-message',
    description: 'React Native flashbar and prime notification alert utility' +
                  'n' +
                  'Works on Android & iOS',
    period: 2500
  });
}

As ordinary, you should use the newline character ( n ) to create multi-line textual content for the flashbar message description. When you run your app with the above code snippet, you will note a multi-line flashbar as follows:

A multi-line flashbar

The above FlashMessage part placement stays the identical in case your app renders a number of app screens with a library like react-navigation. Verify this supply file section as a reference implementation.

In case your app has just one app display screen, the library documentation recommends avoiding world setup with React ref objects as follows:

import React, { useRef } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  Button,
} from 'react-native';
import FlashMessage from 'react-native-flash-message';

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!'
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  }
});

export default App;

The above code invokes the showMessage perform through a ref object with out importing the worldwide perform from the library. We’ll use the ref object-based strategy on this tutorial, since our pattern app has just one display screen. However, it is best to use the primary code snippet strategy above in case your app has a number of screens.

Altering the flashbar sort

Earlier, we noticed a grey flashbar message as a result of we used a default configuration. This flashbar library gives you 5 pre-defined flashbar varieties, so you’ll be able to select one primarily based on the flashbar message severity. Check out the next supported message varieties:

perform Spacer() {
  return (
    <View model={kinds.spacer}></View>
  );
}

perform App() {
  const flashMessage = useRef();
  perform handlePress(sort) {
    flashMessage.present.showMessage({
      message: 'Kind: ' + sort,
      sort
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        model={kinds}
        title="Default"
        onPress={() => handlePress('default')}
        coloration="#696969"/>
      <Spacer/>
      <Button
        title="Success"
        onPress={() => handlePress('success')}
        coloration="#5cb85c"/>
      <Spacer/>
      <Button
        title="Data"
        onPress={() => handlePress('information')}
        coloration="#5bc0de"/>
      <Spacer/>
      <Button
        title="Warning"
        onPress={() => handlePress('warning')}
        coloration="#f0ad4e"/>
      <Spacer/>
      <Button
        title="Hazard"
        onPress={() => handlePress('hazard')}
        coloration="#d9534f"/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  },
  spacer: {
    paddingBottom: 8
  }
});

Right here, we created 5 buttons to indicate all the pre-defined flashbar varieties which are supported. The handlePress perform dynamically units the message sort. Add the above code to your App.js, then run it. You will note the next outcome:

Pre-defined flashbar types

Utilizing customized colours

The sort choice units the background coloration based on pre-defined varieties. For instance, the default message sort renders grey coloration for the background. These pre-defined coloration schemes are UX-friendly and resolve virtually all design necessities, however this library additionally enables you to use customized colours for textual content and background.

For instance, the next code snippet renders a flashbar with customized colours:

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!',
      coloration: '#332222',
      backgroundColor: '#e09107'
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}
        coloration="#e09107"/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  }
});

The above code snippet applies customized textual content and background colours with the coloration and backgroundColor choices, respectively. You will note the next outcome while you run the app:

Background color of flashbar.

Making use of customized kinds to your flashbars

This library routinely applies appropriate colours primarily based on the flashbar message sort whereas adhering to UI/UX ideas. It additionally makes use of some textual content kinds based on the given props, reminiscent of rising the font weight of the message title for those who create a multi-line flashbar with message and description choices.

However in some situations, we have to make additional customizations to perform our design wants. This library enables you to change the message container, title, and outline model definitions through the message object.

model: Altering the message container model

You possibly can change the container model to make use of customized styling for the flashbar field, as proven within the following code snippet:

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!',
      sort: 'success',
      model: kinds.flashMessage
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12,
  },
  flashMessage: {
    borderRadius: 12,
    opacity: 0.8,
    borderWidth: 2,
    borderColor: '#222',
    margin: 12
  }
});

The above code extends the inbuilt success message model and creates a customized flashbar with spherical edges. Have a look at the next preview:

Flashbar with round edges.

Notice: You may also set the floating message object choice to true to make flashbar edges spherical. The above borderRadius prop was used for demonstration functions.

titleStyle and textStyle: Altering textual content kinds

You need to use the titleStyle and textStyle choices to move customized kinds for flashbar message titles and descriptions. For instance, the next code snippet makes use of a daring font model for the title textual content and a small italic font model for the outline textual content:

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!',
      description: 'React Native flashbar and prime notification alert utility',
      sort: 'success',
      titleStyle: kinds.flasdescriptionhTitle,
      textStyle: kinds.flashText
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 16,
  },
  flashTitle: {
    fontWeight: 'daring',
    fontSize: 18
  },
  flashText: {
    fontStyle: 'italic',
    fontSize: 15
  }
});

Run the above code. You will note customized textual content kinds, as proven within the following preview:

Custom text styles.

Utilizing inbuilt and customized icons

Most internet builders typically use icons with alert messages to enhance user-friendliness. For instance, for those who use an appropriate icon and coloration for an error popup, customers know the actual popup’s severity with out studying the complete textual content. Equally, we will use icons in React Native flashbar messages for higher user-friendliness.

By default, this library doesn’t present any icon with flashbars, however you should use one routinely primarily based on the flashbar sort as follows:

perform Spacer() {
  return (
    <View model={kinds.spacer}></View>
  );
}

perform App() {
  const flashMessage = useRef();
  perform handlePress(sort) {
    flashMessage.present.showMessage({
      message: 'Kind: ' + sort,
      sort,
      icon: 'auto'
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Success"
        onPress={() => handlePress('success')}
        coloration="#5cb85c"/>
      <Spacer/>
      <Button
        title="Data"
        onPress={() => handlePress('information')}
        coloration="#5bc0de"/>
      <Spacer/>
      <Button
        title="Warning"
        onPress={() => handlePress('warning')}
        coloration="#f0ad4e"/>
      <Spacer/>
      <Button
        title="Hazard"
        onPress={() => handlePress('hazard')}
        coloration="#d9534f"/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  },
  spacer: {
    paddingBottom: 8
  }
});

The above icon: 'auto' configuration asks the library to make use of an appropriate icon primarily based on the message sort. When you run the above code, you will note flashbar message icons as follows:

Flashbar message icons.

If you need extra management over the inbuilt icon choice, you’ll be able to manually set information, success, warning, and hazard values for the icon choice.


Extra nice articles from LogRocket:


This library is so versatile, it’ll allow you to set any React part because the flashbar icon. Let’s add a vector icon with the react-native-vector-icons library.

Notice: The next code requires an set up of the react-native-vector-icons library. Set up it with the steps talked about within the readme file of the library on GitHub.

Add the next code to your App.js file:

import Icon from 'react-native-vector-icons/FontAwesome';

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!',
      description: 'React Native flashbar and prime notification alert utility',
      sort: 'warning',
      icon: () => <Icon
                    identify="warning"
                    measurement={30}
                    coloration="#aa2020"
                    model={{paddingRight: 20, paddingTop: 14}}
                  />
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}
        coloration="#e09107"/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  }
});

Right here we use a warning signal vector icon from the Font Superior icons pack. The above code will present a customized icon within the flashbar, as proven within the following preview:

Warning sign vector.

Attempt to use a PNG icon with an Picture part occasion — you should use any JSX ingredient within the icon callback.

Altering the flashbar place

Since we used the default place, all earlier flashbars appeared on the highest of the display screen. We will change the flashbar place with the place choice. The place choice accepts prime, proper, backside, and left string values.

Add the next choice to the earlier customized icon setup’s showMessage perform:

place: 'backside'

When you open the flashbar, you’ll discover it on the underside fringe of the display screen, the identical as Android Toast or the default Snackbar setup.

Attaching occasion handlers

Flashbars are sometimes used to show varied alerts and in-app notifications. Alerts are sometimes brief messages that don’t provide additional interactivity, however for those who use flashbars to show in-app notifications, you might have to direct the consumer to a different app display screen as soon as the consumer presses a flashbar message. Or, you might want to indicate an in depth rationalization a couple of explicit flashbar-based error message when the consumer long-presses it.

In these situations, we have to connect occasion handlers to the flashbar. Have a look at the next code to grasp all supported occasion callbacks:

perform App() {
  const flashMessage = useRef();
  perform handlePress() {
    flashMessage.present.showMessage({
      message: 'Hiya flashbars!',
      description: 'React Native flashbar and prime notification alert utility',
      sort: 'information',
      place: 'backside',
      hideOnPress: false,
      period: 5000,
      onPress: () => console.log('occasion: onPress'),
      onLongPress: () => console.log('occasion: onLongPress'),
      onShow: () => console.log('occasion: onShow'),
      onHide: () => console.log('occasion: onHide'),
    });
  }
  return (
    <SafeAreaView model={kinds.container}>
      <Button
        title="Present alert"
        onPress={handlePress}/>
      <FlashMessage ref={flashMessage}/>
    </SafeAreaView>
  );
}

const kinds = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'middle',
    padding: 12
  }
});

We set the hideOnPress prop to false and use a protracted period to experiment with supported occasion handlers. Occasion handlers are executed on the next flashbar and consumer actions:

  • onPress: When the consumer presses the flashbar
  • onLongPress: When the consumer lengthy presses the flashbar
  • onShow: When the flashbar seems
  • onHide: When the flashbar disappears

Run the code above. Faucet or long-press the flashbar. You will note each occasion handler will get executed as follows:

Event handler

Customizing inbuilt animations and creating customized animations

By default, the react-native-flash-message library performs a slide-in/slide-out transition animation while you show the flashbar on the highest or backside of the display screen. In any other case, it can play a fade-in/fade-out transition animation. If you happen to don’t like transition animations, you’ll be able to flip off transition animations as follows:

perform handlePress() {
  flashMessage.present.showMessage({
    message: 'Hiya flashbars!',
    animated: false,
    // -------
  });
}

You possibly can additional customise the inbuilt animation by altering the velocity of the transition animation with the animationDuration choice:

perform handlePress() {
  flashMessage.present.showMessage({
    message: 'Hiya flashbars!',
    animationDuration: 650,
    // -------
  });
}

This package deal enables you to override the default transition animation with a customized animation as follows:

perform handlePress() {
  flashMessage.present.showMessage({
    message: 'Hiya flashbars!',
    animationDuration: 650,
    transitionConfig: (animValue, place) => {
      const opacity = animValue.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1]
      });
      const scaleY = animValue.interpolate({
        inputRange: [0, 1],
        outputRange: [0, 1]
      });
      return {
        opacity,
        rework: [{ scaleY }]
      };
    }
  });
}

The library makes use of the transitionConfig callback perform to create animated kinds for the flashbar container. The callback perform sends two parameters:

  1. Animated.Worth reference
    1. Place of the flashbar

The callback perform expects an animated kinds object because the return worth. Animated.Worth goes from 0 to 1 when the flashbar seems, and goes from 1 to 0 when it disappears. So, it’s attainable to animate the flashbar with any supported animation model prop inside transitionConfig through the interpolate methodology.

For instance, the above code snippet makes use of opacity and scaleY. When you run the above code, you will note a customized transition animation, as proven within the following preview:

Custom transition animation.

Attempt to make extra customized animations for the pattern flashbar with the React Native Animated .Worth API.

Embedding different elements into flashbars

Flashbars sometimes present a title and outline with an appropriate icon. In some situations, although, we have to embed different elements into flashbars to enhance UX and implement design necessities. For instance, as a substitute of letting customers faucet the flashbar to do a specific motion, you’ll be able to add a button for them to faucet.

Have a look at the next pattern code snippet:

perform handlePress() {
  flashMessage.present.showMessage({
    message: 'Hiya flashbars!',
    description: 'React Native flashbar and prime notification alert utility',
    animationDuration: 550,
    place: 'backside',
    renderAfterContent: () => (
      <View model={{alignItems: 'flex-end', paddingTop: 12}}>
        <View model={{width: '30%'}}>
          <Button title="Particulars" onPress={() => {}}/>
        </View>
      </View>
    )
  });
}

The above code snippet will embed a button ingredient throughout the flashbar. Have a look at the next preview:

Button element in flashbar

Equally, you should use renderBeforeContent to embed a customized part earlier than the flashbar content material. The above code snippet makes use of an inline perform for renderAfterContent with inline kinds for demonstration functions, however be certain to separate your elements into capabilities and outline part kinds correctly in stylesheets in your manufacturing apps.

Superior flashbar configurations and options

We’ve mentioned library options that you should use to create any customized flashbar based on your design necessities. You understand how so as to add flashbars with customized colours, kinds, animations, and embedded elements. However the react-native-flash-message library gives much more choices and options for superior use circumstances.

World entry with the FlashMessageManager API

The FlashMessageManager utility class enables you to handle flashbar situations. For instance, the next code snippet disables all upcoming flashbars:

import { FlashMessageManager } from 'react-native-flash-message';
FlashMessageManager.setDisabled(true);

The next code snippet shops the present flashbar reference in ref:

const ref = FlashMessageManager.getCurrent();

Then, you’ll be able to disguise it programmatically:

ref.hideMessage();

Defining your individual flashbar part with the MessageComponent prop

The inbuilt flashbar part enables you to customise through props. If you happen to can’t fulfill your design requirement with the prevailing, inbuilt choices, you’ll be able to implement and hyperlink your individual flashbar part with the library through the MessageComponent prop.

Have a look at the next FlashMessage utilization:

<SafeAreaView model={kinds.container}>
  <Button
    title="Present alert"
    onPress={handlePress}/>
  <FlashMessage ref={flashMessage} MessageComponent=
    {({message}) => (
      <View model={{padding: 20}}>
        <Textual content model={{fontWeight: 'daring'}}>{message.message}</Textual content>
        <Textual content>{message.description}</Textual content>
      </View>
    )}
  />
</SafeAreaView>

The above code renders a minimal flashbar that helps the title and outline solely:

Title and description in the flashbar.

Equally, you can also make your individual flashbar elements primarily based in your necessities. We override solely the flashbar part — animations and world utility capabilities will work as anticipated, so that you don’t have to re-implement them your self. Linking a customized flashbar part is the one factor it is advisable do.

Take a look at all supported message object choices and part props from the official library documentation. Library maintainers might add extra options primarily based on function requests on GitHub.

react-native-flash-message alternate options

Each standard React Native library sometimes has aggressive alternate options. react-native-flash-message is a versatile and fully-featured library that you should use in any React Native app — and customizing react-native-flash-message-based flashbars is really easy.

However the next react-native-flash-message alternate options are additionally price testing due to their aggressive options:

Conclusion

On this tutorial, we realized tips on how to create custom-made flashbars with the favored react-native-flash-message library. Some builders try to make their apps look constant amongst all supported working programs with platform-agnostic GUI parts. In the meantime, some builders have a tendency to make use of platform-specific GUI parts. The react-native-flash-message library is a pure JavaScript package deal that permits you to create constant flashbars on all supported platforms.

We additionally briefly checked out alternate options just like the react-native-simple-toast library, which renders platform-specific, native, flashbar-like toast messages. As in comparison with react-native-flash-message, although, react-native-simple-toast doesn’t assist embedding JSX elements as a result of it’s a easy native toast library , not a fully-featured flashbar library.

The react-native-flash-message library helps embedding JSX elements and gives in depth choices/props for personalisation, and it gives extra versatile options than different alternate options talked about on this article.

So, general, the react-native-flash-message library is an efficient library so as to add trendy, customizable flashbars to your React Native apps. From the UI/UX perspective, the flashbar idea reveals prolonged content material than the normal toast idea, so don’t hesitate to embed buttons or hyperlinks into flashbars.

Flashbars sometimes show low-priority app occasions, so, for important app occasions, a conventional alert field (a modal dialog) is appropriate over the present app display screen. Use flashbars to inform low-priority app occasions to customers with out blocking consumer interplay with the app display screen. Verify the Materials Snackbar specification to study extra concerning the flashbar idea.

LogRocket: Immediately recreate points in your React Native apps.

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

LogRocket additionally helps you improve conversion charges and product utilization by exhibiting you precisely how customers are interacting along with your app. LogRocket’s product analytics options floor the the explanation why customers do not full a specific movement or do not undertake a brand new function.

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