Giter Site home page Giter Site logo

react-native-flash-message's Introduction

react-native-flash-message

Flash Message is a React Native module to help you easily create highly customizable flashbars, top notifications or alerts (with iPhone X, XR, XS and XS Max "notch" support).

Global Demo of Flash Message Component

npm version npm downloads npm licence help this project

Installation

Since the library is a JS-based solution, to install the latest version of react-native-flash-message you only need to run:

npm install --save react-native-flash-message

or

yarn add react-native-flash-message

Try it out

You can try out the Flash Message Playground app to get a tease of the functionalities in this lib.

Basic Usage

The FlashMessage component is built for global use, so you have to instance this component once in your main app screen always as the last inserted component:

import React from "react";
import { View } from "react-native";
import FlashMessage from "react-native-flash-message";

function App() {
  return (
    <View style={{ flex: 1 }}>
      <View ref={"otherView1"} />
      <View ref={"otherView2"} />
      <View ref={"otherView3"} />
      {/* GLOBAL FLASH MESSAGE COMPONENT INSTANCE */}
      <FlashMessage position="top" /> {/* <--- here as the last component */}
    </View>
  );
}

After that you only need to call showMessage or hideMessage methods from anywhere in your app.

If you don't need a global use for (e.g. will use only in one screen) you can instance your FlashMessage Component with a ref ID (or other capture ref method):

<View style={{ flex: 1 }}>
  <YourMainApp />
  <FlashMessage ref="myLocalFlashMessage" />   {/* <--- here as the last component always with `ref` as a prop */}
<View>

Show some message

Now that you already instantiated the global FlashMessage component, when you need to show some message in your app you could use the showMessage method in any screen or view. This is a global method that receive a message object with your message detail:

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

import { showMessage, hideMessage } from "react-native-flash-message";

function MyScreen() {
  return (
    <View style={{ flex: 1 }}>
      <Button
        onPress={() => {
          /* HERE IS WHERE WE'RE GOING TO SHOW OUR FIRST MESSAGE */
          showMessage({
            message: "Simple message",
            type: "info",
          });
        }}
        title="Request Details"
        color="#841584"
      />
    </View>
  );
}

The message object obligatorily requires some message attribute. If you need to show a message with two lines (title and more details) you could use message attr for title and description attr for details line:

showMessage({
  message: "Hello World",
  description: "This is our second message",
  type: "success",
});

The type attribute set the type and color of your flash message, default options are "success" (green), "warning" (orange), "danger" (red), "info" (blue) and "default" (gray).

By default all of the messages will be displayed with transitions and with autoHide after 1850 ms enabled. If you need to programmatically hide any message, you can call hideMessage() .

Other message object attributes will be detailed below.

Props

Property Default In Message Object Description
hideOnPress true Yes Controls if the flash message can be closed on press
onPress none Yes onPress callback for flash message press
onLongPress none Yes onLongPress callback for flash message press
animated true Yes Controls if the flash message will be shown with animation or not
animationDuration 225 Yes Animations duration/speed
autoHide true Yes Controls if the flash message can hide itself after some duration time
duration 1850 Yes How many milliseconds the flash message will be shown if the autoHide it's true
hideStatusBar false Yes Controls if the flash message will auto hide the native status bar. Note: Works OK in iOS, not all Android versions support this.
statusBarHeight none Yes Use this prop to set a custom status bar height that will be add in flash message padding top calc
floating false Yes The floating prop unstick the message from the edges and applying some border radius to component
position top Yes The position prop set the position of a flash message. Expected options: "top" (default), "bottom", "center" or a custom object with { top, left, right, bottom } position
icon none Yes The icon prop could be a render function that return a new JSX Element to be placed in icon position OR a definition of the graphical icon of a flash message. Expected options: "none" (default), "auto" (guided by type), "success", "info", "warning", "danger", a custom icon (render function) or a custom object with icon type/name and position (left or right) attributes, e.g.: { icon: "success", position: "right" }
style none Yes Apply a custom style object in flash message container
textStyle none Yes Apply a custom style object in flash message descript/text text label
titleStyle none Yes Apply a custom style object in flash message title text label
titleProps none Yes Set a custom props object in flash message title text label
textProps none Yes Set a custom props object in flash message all text components
iconProps none Yes Set a custom props object to use inside the renderFlashMessageIcon method as third argument
renderBeforeContent none Yes Render custom JSX before title in flash message.
renderCustomContent none Yes Render custom JSX below title in flash message.
renderAfterContent none Yes Render custom JSX after the title (or description) of a flash message.
renderFlashMessageIcon renderFlashMessageIcon Yes Set a custom render function for inside message icons
transitionConfig FlashMessageTransition No Set the transition config function used in shown/hide anim interpolations
canRegisterAsDefault true No Use to handle if the instance can be registed as default/global instance
MessageComponent DefaultFlash No Set the default flash message render component used to show all the messages

Message Object

When you call showMessage method you'll need to pass a message object to show your message. In this call you could pass some custom attributes to customize your message. Most of the FlashMessage Component props can be passed in runtime calls of showMessage. This common props/attributes are identified in Props table as In Message Object.

If you need to customize de background color or text color of your message beyond the default types (success, warning, info and danger) you could use the backgroundColor or/and color attributes in your message object:

showMessage({
  message: "My message title",
  description: "My message description",
  type: "default",
  backgroundColor: "purple", // background color
  color: "#606060", // text color
});

If you need to handle the press/touch event in your message, you could use the onPress attribute to take some action:

showMessage({
  message: "My message title",
  description: "My message description",
  type: "success",
  onPress: () => {
    /* THIS FUNC/CB WILL BE CALLED AFTER MESSAGE PRESS */
  },
});

Message with custom icon

To show a custom/diferent icon in a showMessage call you could simple pass a render function with a new JSX element to shown:

showMessage({
  message: "Hello World",
  description: "This is our custom icon message",
  icon: props => <Image source={require("../assets/YOUR-CUSTOM-ICON.png")} {...props} />,
  type: "success",
});

Disable all messages

If you need to, for some reason, "turn off" all the flash messages, you could use the FlashMessageManager utility class:

import { FlashMessageManager } from "react-native-flash-message";

// true to disable, false to enable
FlashMessageManager.setDisabled(true);

iPhone X (and above)

The main MessageComponent (responsible for rendering the messages) is DefaultFlash. This component is wrapped in another component called FlashMessageWrapper that handles device orientations, statusbar heights and principal whether or not include the iPhone X "notch" inset padding:

iPhone X

iPhone X Landscape

Documentation

More details and use cases coming soon.

Donation

If this project helped you to reduce your developing time, you can give me a cup of coffee :)

Please, consider becoming a sponsor.

License

MIT

react-native-flash-message's People

Contributors

aadelgrossi avatar abathz avatar berman82312 avatar bradens avatar delltrak avatar dependabot[bot] avatar derekdapp avatar dmkav avatar doaa-ismael avatar evancloutier avatar gmartpad avatar ialirezakml avatar invertedx avatar iroachie avatar joaovpmamede avatar jordanmiguel avatar liamgregory avatar lucasferreira avatar mertohancan avatar mookiies avatar radko93 avatar rollsroyc3 avatar rwoverdijk avatar soupjake avatar srepower avatar toml0006 avatar tyndria avatar vicrac avatar xuqianjin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-flash-message's Issues

Not working with createSwitchNavigator when using react-navigation

This library works flawlessly with createStackNavigator but doesn;t work with createSwitchNavigator.

I have a root layout all my components are wrapped with set like this.

This happens with react-navigation library

render(){

        {
            return this.state.fontLoaded ? 
                (
                    <View style={{flex: 1}}>
                        { this.props.children }
                        <FlashMessage position="top" titleStyle={{ fontFamily: 'maven-pro' }}/>
                    </View>
                ) : null
        }
    }

React.children.only expected to receive a single react element child

My App.js render is

render() {
return (
Provider store={StoreConfig}
RootNavigator/
FlashMessage position="top" /
/Provider
)
}

if i remove FlashMessage position="top" my app is working fine. If i use that step i'm getting the error as 'React.children.only expected to receive a single react element child'

Love this!

Great work on this, its the best message bar implementation of them all. You should be proud.

Multiple message support?

Hi,

Congratulations on your project. If a second (or subsequent) message is displayed while one or more are currently displayed, are the multiple messages shown?

Many thanks,
Larry

Notification does not come down as far on iPhone XR

I see you have custom heights/widths for iPhone X and ipad:

const X_WIDTH = 375; // iPhone X
const X_HEIGHT = 812; // iPhone X
const PAD_WIDTH = 768; // iPad
const PAD_HEIGHT = 1024; // iPad

so it may just mean adding iPhone XR to the mix, but the flash message doesn't appear as clean as iPhone X

iPhone XR
iphonexr

iPhone X/XS
iphonexs

Custom font

Hi,
thanks for this awesome lib. I am wondering if there is a way to customize the fontFace when using a custom font throughout the app?

Thanks,

Message shows underneath modal

I would like to start off by saying that this library is amazing.

I'm having one particular issue that the message shows underneath a modal if a modal is currently open

My current root setup looks like:

  <Provider store={store}>
    <ActionSheetProvider>
      <App />
    </ActionSheetProvider>
  </Provider>

Where App is :

        <View style={{flex: 1}}>
          <AppNavigation
            ref={this.onNavigatorRef.bind(this)}
          />
          <FlashMessage position="top" />
        </View>

Any help would be appreciated, thanks!

[IOS] Text is not shown

Hi there,

I using this lib to show information messages It's working on Android but the text is not shown on IOS, do you have any tips for me ?

react-native-cli: 2.0.1
react-native: 0.59.9
import React, { Component } from 'react';
import { Clipboard, Alert, TouchableOpacity } from 'react-native';
import {
  NavigationStackScreenOptions,
  NavigationScreenProps,
} from 'react-navigation';
import FlashMessage, { showMessage } from 'react-native-flash-message'; // use in app to global use

// SVG
import {
  ArrowLeft,
  ThreeCoins,
  Copy,
} from '@assets/icons';

// services
import i18n from '@services/i18n';
import NavigatorService from '@services/navigation';

// Component
import { StyledText, StyledTitle, StyledView } from '@components/styled';
import {
  AvatarCircle,
  NavHeader,
} from '@components/index';

// constantes
import screens from '@constants/screens';
import colors from '@constants/colors';
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from 'react-native-responsive-screen';

interface IState {

}

interface IProps {
}

interface NavParams {
  referalCode: string;
}

export default class ReferalCode extends Component<
  IProps
  & NavigationScreenProps<NavParams>,
  IState> {
  static navigationOptions = ({
    navigation: {
      state: { params },
    },
  }: NavigationScreenProps<NavParams>): NavigationStackScreenOptions => ({
    header: (
      <NavHeader
        title={i18n.t('refer_friend.page_title')}
        LeftIcon={<ArrowLeft />}
        onLeft={() => params && NavigatorService.goBack()}
        RightIcon={<AvatarCircle />}
        onRight={() => params && NavigatorService.navigate(screens.PROFILE_VIEW)}
      />
    ),
  });

  copyClipboard = (copy: string | undefined) => {
    if (copy) {
      Clipboard.setString(copy);
    }
    showMessage({
      message: i18n.t('refer_friend.copy_code'),
      type: 'info',
    });
  }

  render() {
    const {
      navigation: {
        state: { params },
      },
    } = this.props;

    let _referalCode = params && params.referalCode;
    if (!_referalCode) {
      _referalCode = '';
    }
    return (
      <StyledView
        justify_content="space-around"
        pl={11}
        pr={11}
      >

        <StyledView flex={0.2} pt={6} align="center" justify_content="center">
          <ThreeCoins width={100} height={100} />
          <StyledText
            bold_font
            font_size={5}
            align="center"
            pl={7}
            pr={7}
          > {i18n.t('refer_friend.title')}</StyledText>
        </StyledView>
        <StyledText
          bold_font
          font_size={3.5}
          pl={7}
          pr={7}
          align="center">
          {i18n.t('refer_friend.subtitle')}
        </StyledText>
        <StyledView flex={0.2}>
          <StyledView f_dir="row" align="center" justify_content="center">
            <StyledTitle
              font_size={5}
              align="center"
              pr={2}
            >{i18n.t('refer_friend.code')}</StyledTitle>

            <TouchableOpacity style={{
            }}
              onPress={() => this.copyClipboard(_referalCode)}>
              <Copy height={25} width={25} />
            </TouchableOpacity>
          </StyledView>
          <StyledTitle selectable={true}>{_referalCode}</StyledTitle>
        </StyledView>
        <FlashMessage
          position="bottom"
          animationDuration={225}
          duration={1500}
          floating={true}
          style={{
            borderRadius: 10,
            backgroundColor: colors.KIMBERLY,
            width: wp(50),
            height: hp(2),
            marginLeft: wp(25),
            justifyContent: 'center',
            alignItems: 'center',
          }}
        />
      </StyledView>
    );
  }
}

Thanks

Love this library

Got this up and running and working perfectly in like 30 seconds. Kept me from making it myself. Thanks so much!

One suggestion: it would be nice to add more custom styles, even if it's just a containerStyle and textStyle prop for showMessage.

fontFamily is not working for android title style

Hi , fontFamily is not working for titleStyle on android

//render

<FlashMessage animated={true} textStyle={styles.messageTextStyle} titleStyle={styles.messageTitleStyle} ref="fmLocalInstance" position='top'/>

//style

messageTitleStyle:{
    textAlign:"right",
    color: 'white',
    fontSize:16,
    ...Platform.select({
      ios: {
        fontFamily: "IRANSansMobileNoEn",
        fontWeight: '300',
      },
      android: {
        fontFamily: "IRANSansMobile(NoEn)_Light",
      },
  }),
},

Please solve this issue

duration not working in some android Devices

i'm testing this in Vivo and Samsung device with oreo versions. Here if i set duration to 3000 it's not working. As per the document the default duration is 1850. I guess even this duration is not working. the flash message comes and in no time it goes off. in ios if i check it works fine. Any Suggestions regarding this issue

Export interfaces/types in typescript definitions

Hi,
I'm writing a wrapper around this library (for my project usage). It would be really useful if more definitions were exported like: MessageOptions, MessageType etc.

I could create a PR with above changes, but first I would like to know what you think about it.

Allow specifying zIndex

Otherwise it can sometimes be hidden underneath absolute positioned views that have a higher zIndex.

Flash Message Show Only First Time After Install

I installed react native flash message into my project. Then I'm facing to an issue which flash message only show for the first time after install it. In second time i executed react-native run-android command and I didn't get flash message.

I added this as list component and use follow method to show message. Please help me solve this.

showMessage({
message: "Authentication Failed",
description: "Your token has been expired. Please log again.",
type: "warning",
});

FlashMessage with react-native-router-flux

I'm using react-native-flash-message with react-native-router-flux
I have the following code:

const App = () => (
    <Provider store={store}>
        <Router>
            <Stack>
                <Scene key="splashScreen" component={SplashScreen} initial/>
                <Scene key="welcomeScreen" component={WelcomeScreen}/>
                <Scene key="loginScreen" component={LoginScreen}/>
            </Stack>
        </Router>
    </Provider>
)

AppRegistry.registerComponent(appName, () => App)

I run
Actions.welcomeScreen() and after Actions.loginScreen()

Both components (screens) have the last rendered component:
<FlashMessage floating={true} icon={'auto'}/>

Even if I am on the loginScreen and I run showMessage(), the message is shown on the welcomeScreen;

If the navigation has pushed 3 components and all of them have <Flash Message/>, I want for the message to be shown only on the last pushed component, not on the first that is the case of this scenario.

What should I do in this case?

How import my own style type ?

Hello,

I love this library !!!

I would like if it's possible to import my style for differents type !
I would like change the style type of info, success and error whitout each time pass in my showMessage function my own background style

Do you guys have any idea ?

Thanks

transitionConfig

Hi, could you provide a simple example of how to create own transitionConfig? I want to change easing let us say. Thanks.

Thank You for this library

I was looking for a global alert solution and which I could use with redux without having to pass down ref and stuff, this is exactly what I was looking for.

Thank you, saved a lot of my time 😃

Typescript definitions

Hey! Nice project you've got here. Was wondering if you want to include typescript definitions. I can send the PR for you

borderRightColor not working for android style

borderRightColor not working for android

render

<FlashMessage ref={component => this._registerFMSG = component} textStyle={styles.msgText} titleStyle={styles.msgTitle} position="top" style={styles.flashMsg} renderFlashMessageIcon={() => <RenderFlashMessage/>}/>

style

    width: wp('90%'),
    height: 65,
    borderRadius: 2.5,
    backgroundColor: colors.white,
    shadowColor: "rgba(0, 0, 0, 0.19)",
    shadowOffset: {
      width: -1.7,
      height: 1
    },
    shadowRadius: 3,
    shadowOpacity: 1,
    borderStyle: "solid",
    borderWidth: 0.5,
    borderRightWidth: 5,
    borderRightColor: colors.primary,
    justifyContent: 'flex-end',
    borderColor:  colors.borderShadow
  }, 

any solution for this issue?

Text wrap

Hi, first of all nice component! There's a way to 'word wrap' the text? I upload a photo look that the word ingresa-do is divided! How can I prevent that? Thanks in advance!

image

Using Switch Navigator

How would I add global flash messages if my App.js uses switch navigator?

App.js

import React from 'react'
import { StyleSheet, Platform, Image, Text, View } from 'react-native'
import { SwitchNavigator } from 'react-navigation'
// import the different screens
import Loading from './Loading'
import SignUp from './SignUp'
import Login from './Login'
import Main from './Main'
// create our app's navigation stack
const App = SwitchNavigator(
  {
    Loading,
    SignUp,
    Login,
    Main
  },
  {
    initialRouteName: 'Loading'
  }
)
export default App

I'm also using tab navigator. Do I need to add flash messages for each tab? Or is it possible to add it globally with SwitchNavigator + TabNavigator

StackNavigator not work!

I make StackNavigator.

import React from 'react'
import { createStackNavigator } from 'react-navigation'
import {View} from 'react-native'
import SignInScreen from '../screens/SignInScreen'
import SettingsScreen from '../screens/SettingsScreen'

export default createStackNavigator(
  {
    SignIn: SignInScreen,
    Settings: SettingsScreen
  },
  {
    navigationOptions: {
      headerStyle: {
        backgroundColor: '#0e376b',
        elevation: 0
      },
      headerRight: <View/>,
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
        flex: 1, textAlign: 'center'
      }
    }
});

the SettingScreen is from signInScreen

//  signInScreen.js
this.props.navigation.navigate('Settings')

and in settingScreen.js,i use showMessage,howerver it notwork, but show in the signInScreen

showMessage({
        message: "message",
        description: "description",
        backgroundColor: '#018ee0',
        type: "info",
 })
  <FlashMessage ref="setting"/>

how to fixed it?

How to use built-in icon?

I've tried with below but the Icon doesnt render

showMessage({
  icon: { icon: 'danger' },
  message: 'Verification failed',
  type: 'danger'
});

Issue with renderCustomContent

Hello,

Thank you for creating this package, it is very helpful! Unfortunately I wasn't able to get renderCustomContent to work and I found that I had to change line 228 in FlashMessage.js to
{!!message.renderCustomContent && message.renderCustomContent()} in order for it to work. Maybe this is something that you could look into? Thank you so much! :)

How do we access a non-global flash-message?

I have figured out how to access the global FlashMessage component.

However, I want to have a second FlashMessage component positioned in another View in another screen.

I realize that the non-global FlashMessage is supposed to be like below with a ref. But, how do I access the non-global FlashMessage to show a message?

<FlashMessage ref="myNonGlobalFlashMessage" /> 

Or am I doing something completely wrong?
What I am trying to accomplish is, I want to have this FlashMessage in a scrollview under the Header. So, I wrapped up my ScrollView with a View, and put the FlashMessage under the ScrollView. Pretty much like below,

<View>
  <ScrollView> ...</ScrollView>
  <FlashMessage.. />
</View>

But, I can't get it to show a message.

Using with react-native-navigation

When i use it with RNN it's looks like this:
image

How i implement:

const ProviderWrap = Comp => props => (
  <View>
    <Comp {...props} />
    <FlashMessage position="top" hideStatusBar={true} />
  </View>
);
Navigation.registerComponent("Login", () => ProviderWrap(Login));

Defining refs don't seem to work

I tried initialising FlashMessage with ref, and it doesn't seem to work.
<FlashMessage ref="signin" position="top" duration={5000} />
<FlashMessage ref="signup" position="top" duration={5000} />

Padding issue when using icon

When displaying a long message and using an icon and floating property the container is lacking right padding. This is not an issue when the icon is hidden. Other than that I love this plugin!

Where to set in DrawerNavigation

I want to use this type of message but it does not work properly...
I know you have to put some were globally but i can't figure it out..
When i show the message is like in the pictures.
screenshot_1545928539

This is my App.tsx:

`import * as React from 'react';
import { Dimensions } from 'react-native';
import { DrawerNavigator } from 'react-navigation';

import SideMenuComponent from './side-menu/side-menu.component';
import { stackNavigator } from './stack.navigator';

const App = DrawerNavigator({
App: {
screen: stackNavigator
}
}, {
contentComponent: SideMenuComponent,

drawerWidth: Dimensions.get('window').width * 0.8

});

export default App;`

Callback on animation complete?

Hi, thank you for this awesome component! Just wondering if there is a way to call a function when the message animation is done? (I'd like to be able to trigger an action in my UI when the message hides itself.) Thanks again!!

Style

How can I add styles to this flash message?
I want to change font size and ...

Disable on some scenes/components

Hi there,

I see there is a hideMessage method, is there a way to disable the popups from happening on a specific screen?

Scenario: a user is still getting message notifications when they are in the chat.

I am showing the message from App.js, and wishing I could disable it from anywhere.

Cheers.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.