Git Product home page Git Product logo

react-native-message-bar's Introduction

react-native-message-bar

npm version Codacy Badge downloads license Platform

A message bar notification component displayed at the top of the screen for React Native (Android and iOS) projects.

Screenshot

Content

Features

  • Android and iOS capable
  • Animated alert with Title, Message and Icon/Avatar (from a local or a remote image file)
  • Top or Bottom display
  • 4 Slides Animation Types (Alert is shown from top, from bottom, from left or from right)
  • Auto-hide after x seconds (customizable and/or can be disabled)
  • Auto-hide current alert to display a newer one, if context requires to do so
  • Support hide on tap (can be disabled)
  • 4 pre-configured customizable styles + 1 extra
  • Customizable texts, styles, durations, positions and animation
  • Callbacks on alert show, hide and tap
  • Orientation supported
  • Children component support Show/Hide alert

Installation

Make sure that you are in your React Native project directory and run:

$ npm install react-native-message-bar --save

Basic Usage

    1. Import the react-native-message-bar package
var MessageBarAlert = require('react-native-message-bar').MessageBar;
var MessageBarManager = require('react-native-message-bar').MessageBarManager;
    1. Add the MessageBarAlert to your render function Note: Add it at the very end of your render function, the alert will then be displayed over any component of the view
// Within your render function.
// Include the MessageBar once within your top View element
// Make sure you add the MessageBar at the very bottom of your master component, then it will be displayed over all other components
<MessageBarAlert ref="alert" />
    1. Register and Release your Message Bar as the current main alert
componentDidMount() {
  // Register the alert located on this master page
  // This MessageBar will be accessible from the current (same) component, and from its child component
  // The MessageBar is then declared only once, in your main component.
  MessageBarManager.registerMessageBar(this.refs.alert);
}

componentWillUnmount() {
  // Remove the alert located on this master page from the manager
  MessageBarManager.unregisterMessageBar();
}
    1. Display the Message Bar Alert on demand
// Call this method after registering your MessageBar as the current alert
// By calling this method the registered alert will be displayed
// This is useful to show the alert from your current page or a child component
MessageBarManager.showAlert({
  title: 'Your alert title goes here',
  message: 'Your alert message goes here',
  alertType: 'success',
  // See Properties section for full customization
  // Or check `index.ios.js` or `index.android.js` for a complete example
});

Please note, if you do not provide a alertType, the info one will be chosen for you.

The normal duration of the notification is 3 seconds (3000 ms), you can override it. After this time, the notification is going to be hidden

See a full Example in index.ios.js or index.android.js.

Hide the Message Bar Alert

// You can force the current alert to be hidden through the Manager
MessageBarManager.hideAlert();

Customize Alert Type

The Message Bar Alert comes with 4 pre-configured alert style and 1 undefined extra. These alert styles defined the background color of the alert and the line stroke color. The 4 pre-configured alert styles are:

  • info defined blue colors
  • success defined green colors
  • warning defined orange colors
  • error defined red colors

The extra alert type allows you to use another 5th type.

MessageBarManager.showAlert({
  ...

  alertType: 'info', // Alert Type: you can select one of 'success', 'error', 'warning', 'error', or 'custom' (use custom if you use a 5th stylesheet, all are customizable). Default is 'info'

  /* Customize the stylesheets and/or provide an additional one 'extra' */
  stylesheetInfo : {{ backgroundColor : '#007bff', strokeColor : '#006acd' }}, // Default are blue colors
  stylesheetSuccess : {{ backgroundColor : 'darkgreen', strokeColor : '#b40000' }}, // Default are Green colors
  stylesheetWarning : {{ backgroundColor : '#ff9c00', strokeColor : '#f29400' }}, // Default are orange colors
  stylesheetError : {{ backgroundColor : '#ff3232', strokeColor : '#FF0000' }}, // Default are red colors
  stylesheetExtra : {{ backgroundColor : 'black', strokeColor : 'gray' }}, // Default are blue colors, same as info

  ...
});

Customize Alert Content

You can customize the style of the Title, Message and Icon/Avatar.

MessageBarManager.showAlert({
  ...

  title: "John Doe", // Title of the alert
  message: "Hello, any suggestions?", // Message of the alert
  avatar: "<URL/require('<path>') of your icon/avatar>", // Avatar/Icon <URL> of the alert or enter require('LOCALPATH') for local image

  /* Number of Lines for Title and Message */
  titleNumberOfLines: 1,
  messageNumberOfLines: 0, // Unlimited number of lines

  /* Style for the text elements and the  */
  titleStyle: {{ color: 'white', fontSize: 18, fontWeight: 'bold' }},
  messageStyle: {{ color: 'white', fontSize: 16 }},
  avatarStyle: {{ height: 40, width: 40, borderRadius: 20 }},

  ...
});

Customize Message Bar Alert Layout

You can customize the inset (padding) and the offset of the alert.

MessageBarManager.showAlert({
  ...

  /* Offset of the View, useful if you have a navigation bar or if you want the alert be shown below another component instead of the top of the screen */
  viewTopOffset : 0, // Default is 0
  viewLeftOffset : 0, // Default is 0
  viewRightOffset : 0, // Default is 0

  /* Inset of the view, useful if you want to apply a padding at your alert content */
  viewTopInset : 15, // Default is 0
  viewLeftInset : 0, // Default is 0
  viewRightInset : 0, // Default is 0

  ...
});

Customize Position and Animation, Twitter Style!

You can choose the position (topor bottom) of the alert. You can choose the way the alert is shown (SlideFromTop, SlideFromBottom, SlideFromLeft or SlideFromRight).

MessageBarManager.showAlert({
  ...

  /* Position of the alert and Animation Type the alert is shown */
  position: 'bottom',
  animationType: 'SlideFromLeft',

  ...
});

Properties

Prop Type Default Description
title String Title of the alert
message String Message of the alert
avatar String Avatar/Icon source/URL of the alert. Use for a remote image file (eg avatar: 'http://mywebsite.com/myimage.jpg') or use avatar: require('<path/to/my/local/image.extension>') for a remote image file
alertType String info Alert Type: you can select one of 'success', 'error', 'warning', 'error', or 'custom' (use custom if you use a 5th stylesheet, all are customizable).
duration Number 3000 Number of ms the alert is displayed
shouldHideAfterDelay Bool true Tell the MessageBar whether or not it should hide after a delay defined in the duration property. If false, the MessageBar remain shown
shouldHideOnTap Bool true Tell the MessageBar whether or not it should hide or not when the user tap the alert. If false, the MessageBar will not hide, but the onTapped function is triggered, if defined. In addition, if false, the onHide function will not be triggered. The property shouldHideAfterDelay take precedence over shouldHideOnTap. That means if shouldHideAfterDelay is false, the value of shouldHideOnTap is not taken into account, since the MessageBar will not ever be hidden
onTapped Function Callback function after alert is tapped
onShow Function Callback function after alert is shown
onHide Function Callback function after alert is hidden
stylesheetInfo Object { backgroundColor: '#007bff', strokeColor: '#006acd' } Background color and line stroke colors of the alert when alertType is equals to info
stylesheetSuccess Object { backgroundColor: 'darkgreen', strokeColor: '#b40000' } Background color and line stroke colors of the alert when alertType is equals to success
stylesheetWarning Object { backgroundColor: '#ff9c00', strokeColor: '#f29400' } Background color and line stroke colors of the alert when alertType is equals to warning
stylesheetError Object { backgroundColor: '#ff3232', strokeColor: '#FF0000' } Background color and line stroke colors of the alert when alertType is equals to error
stylesheetExtra Object { backgroundColor: '#007bff', strokeColor: '#006acd' } Background color and line stroke colors of the alert when alertType is equals to extra
durationToShow Number 350 Duration of the animation to completely show the alert
durationToHide Number 350 Duration of the animation to completely hide the alert
viewTopOffset Number 0 Offset of the view from the top. That means the alert touch the top edge of the screen.
viewBottomOffset Number 0 Offset of the view from the bottom. That means the alert touch the bottom edge of the screen
viewLeftOffset Number 0 Offset of the view from the left. That means the alert touch the left edge of the screen
viewRightOffset Number 0 Offset of the view from the right. That means the alert touch the right edge of the screen
viewTopInset Number 0 Padding Top of the view
viewBottomInset Number 0 Padding Bottom of the view
viewLeftInset Number 0 Padding Left of the view
viewRightInset Number 0 Padding Right of the view
titleNumberOfLines Number 1 Number of lines of the title. 0 means unlimited
messageNumberOfLines Number 2 Number of lines of the message. 0 means unlimited
avatarStyle Style { height: 40, width: 40, borderRadius: 20, alignSelf: 'center' } Style of the icon/avatar
titleStyle Style { color: 'white', fontSize: 18, fontWeight: 'bold' } Style of the title
messageStyle Style { color: 'white', fontSize: 16 } Style of the message
position String top Define the position of the alert, can be top or right
animationType String SlideFromTop Define the way the alert is animated on the view, can be SlideFromTop, SlideFromBottom, SlideFromLeft or SlideFromRight. If no value is specified, the animation type is selected for you based on the position; SlideFromTop if position is equal to top, SlideFromBottom if position is equal to bottom. The alert will then be smoothly displayed

Contributing

  1. Fork this Repo first
  2. Clone your Repo
  3. Install dependencies by $ npm install
  4. Checkout a feature branch
  5. Feel free to add your features
  6. Make sure your features are fully tested
  7. Publish your local branch, Open a pull request
  8. Enjoy hacking <3

TODOS

  • Add Alert Queuing System
  • Add Bottom Position
  • Add Slide Animations Type (Slide from Top, Bottom, Left, Right)
  • Add Other Animations Type (Fade-in, Elastic, etc.)
  • Add customizable Animation (inject your configuration)
  • Anything that can help to improve :) Thanks for contributions

Apps using this library

  • Your App here...

License

React-Native-Message-Bar is released under MIT License. See LICENSE for details.

Copyright © 2016 KBLNY.

Please provide attribution, it is greatly appreciated.

react-native-message-bar's People

Contributors

cpunion avatar kblny avatar sgaurav 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

react-native-message-bar's Issues

messageStyle not shown if stylesheet is set

If I have this, the messageStyle seems to be ignored. However, if i remove stylesheetError the properties in messageStyle show up.
messagebar.MessageBarManager.showAlert({ message: 'There was a problem loading your data', alertType: 'error', stylesheetError: { backgroundColor: '#FF5532', strokeColor: '#FF5532' }, messageStyle: { color: 'white', fontSize: 16 }, });

MessageBar is being displayed on component mount

After upgrade RN to 0.30.0, I noticed the MessageBar is being displayed without actually use MessageBarManager for this (e.g. component mount).

Here's a screenshot which better describe the issue:

img-20160729-wa0001

Once I start typing anything on textinputs, which causes the component to rerender, the MessageBar automatically dissappear.

How to use it with react-native-router-flux

Hi, can you please show an example of how to use your component with react-native-router-flux?

Should I use it like this?

import {Scene, Router} from 'react-native-router-flux';

class App extends React.Component {
  render() {
    return <Router>
      <Scene key="root">
        <Scene key="login" component={Login} title="Login"/>
        <Scene key="register" component={Register} title="Register"/>
        <Scene key="home" component={Home}/>
      </Scene>

     // Within your render function.
     // Include the MessageBar once within your top View element
     // Make sure you add the MessageBar at the very bottom of your master component, then it will be           displayed over all other components
     <MessageBarAlert ref="alert" />

    </Router>
  }
}

messageBar shows behind listview

There is a listview to load data, when these datas are loaded, I want to show a message bar to notice user the status of the result, but the bar is showing behind the listview.

If the message bar element placed after listview, then the bar would show at the bottom with the screen as this listview is being full with datas

So, what should I do ?

The main code is like this:

      <View
        style = {styles.container}
      >
        <View>
          <MessageBar style={{position: 'absolute'}} ref='messageAlert' />
        </View>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this.getExamCell}
          enableEmptySections={true}
          stickySectionHeadersEnabled = {false}
          renderSectionHeader={this.renderSectionHeader}
        />
       </View>
componentDidMount() {
    MessageBarManager.registerMessageBar(this.refs.messageAlert)
  }

  componentWillUnmount() {
    MessageBarManager.registerMessageBar(this.refs.messageAlert)
  }

The code to fetch data:

renderExamDatasource = (url) => {
    fetch(url).then((response) => (response.json()))
    .then((jsonBody) => {
      let local = [array.first(jsonBody.param)]
      if (jsonBody.success) {
        MessageBarManager.showAlert({
          title: '加载成功',
          message: '共为你获取到' + (jsonBody.param.length + local.length) + '条数据',
          alertType: 'info',
        })
      } else {
        MessageBarManager.showAlert({
          title: 'error',
          message: jsonBody.param ? 'unknow reason' : jsonBody.param,
          alertType: 'warning',
        })
      }
    })
    .catch(reason => {
      MessageBarManager.showAlert({
        title: '加载错误',
        message: '网络错误,无法加载到您所需的数据',
        alertType: 'warning',
      })
    })
  }

The screenshot is like this:
simulator screen shot 2018 1 28 9 26 38

Where is the author

I find this component quite useful but it seems @KBLNY has stopped maintaining it. Has anyone considered maintaining a fork of this component?

2.0.10 - componentWillReceiveProps lifecycle warning with react-native 0.61.x

YellowBox.js:71 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

* Move data fetching code or side effects to componentDidUpdate.
* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: MessageBar

The message bar shows up behind Modal component.

Is this the desired behavior? I'm looking for some messaging library that I can plop into one spot and have access to app-wide.

However, I've noticed that this appears to be a common theme: user feedback messages always being behind Modals.

Any guidance?

Can't custom color for titleStyle

When I custom stylesheet background, the background is work as my expected but the color of title and message change to the dark color. Even I change the textStyle, it still not working. Do u guys have any idea to fix this? Tks in advance.

Here is my code:

MessageBarManager.showAlert({
title: customTitle,
message: customMessage,
alertType: 'info',
duration: 5000,
durationToShow: 500,
onTapped: this.state.actionCallback,
stylesheetInfo: {backgroundColor: '#4065b5', strokeColor: '#4065b5'},
titleStyle: {color: 'white', fontSize: 18, fontWeight: 'bold'},
messageStyle: {color: 'white', fontSize: 16},
});

screenshot_1516198674

Remove log message

Is possible to remove the log message in _apllyAnimationTypeTransformation method?
Thanks.

Delayed message

Hi,
Message have 2 seconds delay before it shows up after calling it. What can cause that delay? I test it on emulator as well on real device.

Thanks

Edit:
Okay, so it's little bit faster by adding these:
durationToShow: 0, durationToHide: 0
but it's still not satisfying as after spinner there is delay that I'd like to get rid of if possible.

Difficulties Using in Project - Messages Do Not Appear

Hello,

I'm attempting to integrate your snazzy library into my project, but am having some difficulties getting the message to actually show up in the application.

I've setup the project as the README describes (and validated against the AppTest.js file), and also have attempted to adjust the position of the message (by setting the viewTopOffset to +/- 300 and position to bottom on the showAlert() method). None of those seemed to give a sign as to what might be going wrong.

You can view my implementation of the code: https://github.com/AndrewZurn/spac-fusion-app/blob/master/src/modules/profile/ProfileView.js

Mostly standard React-Native + Redux. I have a Nav and Tab bar, but I'm not sure if those could be causing the issue.

If there is anything you see, or something that could be the source of a bug, please let me know. I've given it a pass or two (both my code again and the code in your classes/components), but was not able to find anything that might be of issue.

Thanks,

Andrew

titleStyle and MessageStyle is not applied when stylesheetSuccess is used

Hi,
Am facing an issue where alertType is success and when there is stylesheetSuccess applied, titleStyle and MessageStyle (where color: 'white') is not applied. Any advise?

showInAppAlert(title, message, callbackFunction){ MessageBarManager.showAlert({ title : title, message: message, alertType: 'success', avatar: <${this.state.userIcon.uri}>, duration : 20000, viewTopOffset : 0, viewTopInset : 20, onTapped:()=>{callbackFunction()}, stylesheetSuccess : { backgroundColor: '#32A54A', fontSize: 16}, titleStyle : { color : 'white', fontSize : 16, fontFamily : Fonts.type.bold, fontWeight : 'bold', marginBottom : 2, }, messageStyle : { color : 'white', fontFamily : Fonts.type.base, fontSize : 14, marginBottom : 2 }, avatarStyle: { height: 40, width: 40, borderRadius: 20 }, messageNumberOfLines : 5, }); }

Cannot read property 'hideMessageBarAlert' of undefined

Whenever I trigger an alert nothing seems to happen and I get this:

Possible Unhandled Promise Rejection (id: 0): Cannot read property 'hideMessageBarAlert' of undefined TypeError: Cannot read property 'hideMessageBarAlert' of undefined at Object.module.exports.hideAlert (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:16093:29) at Object.module.exports.showAlert (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:16071:6) at _callee2$ (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:80269:512) at tryCatch (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5108:30) at GeneratorFunctionPrototype.invoke [as _invoke] (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5384:12) at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5141:13) at tryCatch (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5108:30) at invoke (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5184:12) at http://localhost:8081/index.ios.bundle?platform=ios&dev=true:5229:1 at tryCallTwo (http://localhost:8081/index.ios.bundle?platform=ios&dev=true:2626:1)

borderRadius for a view

is it possible to set up the borderRadius for a view?
like:
stylesheetInfo : {{ backgroundColor : '#007bff', strokeColor : '#006acd' , borderRadius: 20}}`

Is it possible to dispatch the ShowAlert function through the reducer?

I'm trying to use the ShowAlert function for logout success messages and error messages. The problem is my actions are tucked away in another file that isn't a child component of my the main parent component. Is there any way to feed the Alert action through the redux store and have RegisterMessageBar function listen for the alert? I didn't know how to classify this as a question as opposed to an issue. I realize in the documentation it specifically mentions it needs to be a child component but I still thought I'd try my luck and ask. Thanks in advance!

Display notification in all screens

Notification only pops up when user is in Main screen (HomeScreen). But when user navigates to other pages, notification is received but alert is not displayed.

Cannot read property 'setNewState' of undefined

Hello -

Thanks for this. I am surely missing something basic, but when I try to display an alert, the showCurrentAlert function of MessageBarManager barfs @ line 47 - "Cannot read property 'setNewState' of undefined.

My project is set up with a redux store and a router. When I just drop your example code into my project, it works fine.

Kaveh

在多个组件中怎么使用?

在多个组件中怎么使用?我现在两个页面都要显示messagebar,但是从第二个页面返回回来的时候,第一个页面的messagebar就不显示了。

Blue bar behind status bar

Related to #6 (which is apparently closed) and probably #19 and there is PR #27 but for different kind of issue (or maybe it's same cause but different behavior).

I have this issue too. I have set status bar background to be transparent. After message is shown and I click on TextInput so keyboard is visible, message goes up and there is blue background under status bar (until message goes away - message never goes down again even if you hide keyboard).

Are we still waiting for this fix or is this the new issue?
Thanks

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.