Code Monkey home page Code Monkey logo

react-native-easy-toast's Introduction

react-native-easy-toast

A react native module to show toast like android, it works on iOS and Android.

release PRs Welcome NPM version License MIT 语言 中文

Content

Installation

  • 1.Run npm i react-native-easy-toast --save
    • or yarn add react-native-easy-toast
  • 2.import Toast, {DURATION} from 'react-native-easy-toast'

Demo

Screenshots

Getting started

Add react-native-easy-toast to your js file.

import Toast, {DURATION} from 'react-native-easy-toast'

Inside your component's render method, use Toast:

 render() {
     return (
         <View>
             ...
            <Toast ref={(toast) => this.toast = toast}/>
         </View>
     );
 }

Note: Be sure to add Toast to the bottom of the root view.

Then you can use it like this:

this.toast.show('hello world!');

That's it, you're ready to go!

show a toast, and execute callback function when toast close it:

this.toast.show('hello world!', 500, () => {
    // something you want to do at close
});

Show a toast forever until you manually close it:

this.toast.show('hello world!', DURATION.FOREVER);

Or pass an element:

this.toast.show(<View><Text>hello world!</Text></View>);
 // later on:
 this.toast.close('hello world!');

Optional you can pass a delay in seconds to the close()-method:

 this.toast.close('hello world!', 500);

Currently, the default delay for close() in FOREVER-mode is set to 250 ms (or this.props.defaultCloseDelay, which you can pass with)

 <Toast ... defaultCloseDelay={100} />

Basic usage

render() {
return (
    <View>
        <Button title={'Press me'} onPress={()=>{
            this.toast.show('hello world!',2000);
        }}/>
        <Toast ref={(toast) => this.toast = toast}/>
    </View>
);
    }

Custom Toast

render() {
    return (
        <View>
            <Button title={'Press me'} onPress={()=>{
                    this.toast.show('hello world!',2000);
                }}/>
            <Toast
                ref={(toast) => this.toast = toast}
                style={{backgroundColor:'red'}}
                position='top'
                positionValue={200}
                fadeInDuration={750}
                fadeOutDuration={1000}
                opacity={0.8}
                textStyle={{color:'red'}}
            />
        </View>
    );
}

More Usage:

GitHubPopular

API

Props Type Optional Default Description
style View.propTypes.style true {backgroundColor: 'black',opacity: OPACITY,borderRadius: 5,padding: 10,} Custom style toast
position PropTypes.oneOf(['top','center','bottom',]) true 'bottom' Custom toast position
positionValue React.PropTypes.number true 120 Custom toast position value
fadeInDuration React.PropTypes.number true 500 Custom toast show duration
fadeOutDuration React.PropTypes.number true 500 Custom toast close duration
opacity React.PropTypes.number true 1 Custom toast opacity
textStyle View.propTypes.style true {color:'white'} Custom style text
Method Type Optional Description
show(text, duration, callback, onPress) function false show a toast,unit is millisecond,and do callback
close() function - start the close timer

Contribution

Issues are welcome. Please add a screenshot of bug and code snippet. Quickest way to solve issue is to reproduce it on one of the examples.

Pull requests are welcome. If you want to change API or making something big better to create issue and discuss it first.


MIT Licensed

react-native-easy-toast's People

Contributors

alphasp avatar chenmo230 avatar crazycodeboy avatar darmody avatar immayankraj avatar itinance avatar pigarevaoks avatar scue avatar skinet2009 avatar smiche avatar snyk-bot avatar wangjiejacques 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-easy-toast's Issues

showPermanent method

Hey, such great component, thank you.

By the way, I need to fully control displaying toast, so I made little changes, just added showPermanent method. This could be a cool feature in your package.
feb-22-2017 13-12-09

Best regards, john

多次调用体验不佳

可以在每次show之前做一下判断,在上次duration未结束前close掉,然后再打开新的toast

duration can't be changed

Awesome project! But the toast last on the screen for around 6 seconds with all kinds of durations.
I've tried 100, 500, length_short, length_long. any idea?

Element type is invalid: expected a string ( for built-in compoennts) or a class/function (for compsinte compeonts. but got : object.

I'm using expo to use this component and i keep getting this error:

Can you please let me know what am i doing wrong ?

image

import React, {Component} from 'react';
import {
TouchableHighlight,
StyleSheet,
Text,
View,
} from 'react-native';

import Toast, {DURATION} from 'react-native-easy-toast'

export default class examples extends Component {
constructor(props) {
super(props);
this.state = {
position: 'bottom',
style:{},
}
}

onClick(text, position, duration,withStyle) {
    this.setState({
        position: position,
    })
    if(withStyle){
        this.refs.toastWithStyle.show(text, duration);
    }else {
        this.refs.toast.show(text, duration);
    }
}

getButton(text, position, duration,withStyle) {
    return(
        <TouchableHighlight
            style={{padding: 10}}
            onPress={()=>this.onClick(text, position, duration,withStyle)}>
            <Text>{text}</Text>
        </TouchableHighlight>
    )
}
render() {
    return (
        <View style={styles.container}>
            <Toast ref="toast" position={this.state.position}/>
            <Toast ref="toastWithStyle" style={{backgroundColor:'red'}} position={this.state.position}/>
        </View>
    );
}

}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
});

Toast appears behind tabs on iOS when using React Navigation TabNavigator

When using the React Navigation TabNavigator on iOS (https://reactnavigation.org/docs/navigators/tab) the tabs appear at the bottom of the screen. When the Toast appears in the default position of "bottom" the Toast appears behind the tabs.

Changing the zIndex of the Toast style doesn't seem to make any difference.

The only way I've been able to manage this for now is using the positionValue to raise the position of the Toast above the tabs.

Can't call setState

with the example from the readme:

this.refs.toast.show('Time was added successfully.');

I get this:

ExceptionsManager.js:71 Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in Toast (at ConfirmScene.js:102)
    in RCTView (at View.js:60)
    in View (at ConfirmScene.js:55)
    in ConfirmScene (created by Connect(ConfirmScene))
    in Connect(ConfirmScene) (at SceneView.js:17)

RN is version is 0.55.3

Toast 在多个页面navigate之后就不生效了

我有一个跟页面 里边定义了 Toast 然后使用
this.subscription = DeviceEventEmitter.addListener('toastInfo', (info) => {
this.refs.toast.show(info,10000)
}) 定义监听。
如果在当前页面使用 DeviceEventEmitter.emit('toastInfo','通知来了') Toast 能正常显示
如果在其第n个子页面 使用DeviceEventEmitter.emit('toastInfo','通知来了') Toast就不能正常显示了,
页面跳转使用的是 react-navigation

EventEmitter is outdate

After upgrading React Native from 0.29 to 0.30, EventEmitter is outdate. Now, I get this error message 'Module does not exist in the module map'

Toast message not showing in Android devices

Hi,
Using react-native-easy-toast": "^1.1.0, toast position bottom, the toast message is not appearing in Android devices but works fine in iOS devices.

Does anyone have any workaround to solve this issue? Any suggestion is appreciable.

Thanks

新版本react兼容性警告

Warning: View.propTypes has been deprecated and will be removed in a future version of ReactNative. Use ViewPropTypes instead.

.

top
并不是在上面显示的,用的iOS模拟器

Toast Message off screen in long lists

Hi, I'm trying to use easy-toast and it works very well. But there is one instance I have of a long flatlist. If the list is rather long, I realized that the toast message appears but it is off the screen and you have to scroll in order to see it. Not sure if I am doing something wrong. Here is the code. I have used this on an Android device.

renderHeaderList() {
return (

  <View style={{ flex: 1 }}>

    <ScrollView
      ref={(c) => { this.scroll = c; }}
    >

      <FlatList
        ref={(ref) => { this.flatListRef = ref; }}
        data={{ g_data }}
        renderItem={this.renderItem}
        keyExtractor={(item) => item.srNo}
      />

  </ScrollView>

  <Toast
    ref="toast"
    position={'top'}
    style={{ backgroundColor: 'red' }}
  />

  </View>
);

}

Keyboard open

When keyboard is open the toast is behind the keyboard. it should be over the keyboard

Toast doesn't shows up

I am getting this issue that toast doesn't shows up but the callback is called. I have added toast in the bottom of the component.

open android release package crash

crash reason: undefined is not object

I found the error code
View.propTypes.style
Text.propTypes.style

I comment this line, works fine.

Maybe View.propTypes is not support in lastest React-native version?

Toast message not working as expected while navigating

I'm trying to add a toast message on successful signup. However, the toast message doesn't stick to the screen for the mentioned amount of time(in my case 2000ms). It is instantaneously going to the next line to navigate to the next page and hence the toast message is only displayed for split second. Any idea, how to tackle this?

this.refs.toast.show('User added successfully', 2000); this.props.navigation.navigate('LoginScreen');

简便 使用方法

如果 您 不想 在 每次 都在要 显示 toast 的控件 的 render 方法里 画 控件, 可 把 这句 画在 你的 根控件的 render方法里 ,比如

  <View style={styles.container}>
                <StatusBar translucent={false} backgroundColor={Colors.blue}/>
                <Navigator
                    ref={component => this.navigator = component}
                    initialRoute={
                    {
                        component: RootPagesContainer
                    }
                    }
                    configureScene={this.handlerConfigureScene}
                    renderScene={this.renderScene}
                />
                <Toast ref="toastWithStyle" style={{backgroundColor: Colors.appUnifiedBackColor /*, opacity: 0.8*/ }}
                       textStyle={{
                           fontSize: 20,
                           color: Colors.white,fontWeight:'bold'
                       }} position={'center'}/>
            </View>

然后 在这个根控件监听 一个 showToast事件, 如

componentDidMount() {
this.listener = DeviceEventEmitter.addListener('showToast', (text) => {
this.refs.toastWithStyle.show(text, DURATION.LENGTH_LONG);
});
}

componentWillUnmount() {
    if (this.listener) {
        this.listener.remove();
    }
}

这样在任何地方 都可以调 DeviceEventEmitter.emit('showToast', showMsg);发一个 通知,根控件上就会画这个 toast 控件了

Toast after closing screen

Hey. Is it possible to show same toast, after navigating to another screen? I have problem that my toast is closed after I navigate to different screen.

Render after multiple calls to show seem unintentionally delayed

When calling the show function after the toast has disappeared, the second/3rd/n-th toast is rendered with some unexpected delay

<Button 
  title="Press Me" 
  onPress={()=>{
      console.log("will present toast " + new Date());  
      this.refs.toast.show(""+new Date(),100) 
   }}>
</Button>

<Toast 
   ref="toast"
  position={'top'}
/>

modal toast

Hi @crazycodeboy,
great package - easy to use

one question, issue, how can I make the toast modal?
I don't want the user will be able to scroll, for example, the screen behind?

thanks

Showing twice in quick succession, but doesn't extend the duration...

Actual behaviour:

If I run the following code...

this._toast.show('Message One', 1000)
// wait 500ms
this._toast.show('Message Two', 5000)

The second message text will replace the first, however the toaster popup will still fade 500ms later (total 1 second, instead of the 5 seconds supplied).

Expected behaviour:

When running the second "show", the message text changes, AND the popup stays open for a further 5 seconds.

Is there a way to cancel or reset the existing timer countdown?
(Preferably other than manually using setTimeout/clearTimeout.)

Usage:

<Toast 
  ref={c => this._toast = c}
  style={{backgroundColor: 'red', width: _windowWidth - 20}}
  position='top'
  positionValue={20}
  fadeInDuration={1000}
  fadeOutDuration={1000}
  opacity={1}
  textStyle={{color: 'white'}}
/>

Use Toast React Hooks

The toast will not work with the new version of React Native, who is working with Hooks, the ref of the toast does not you can add the useRef.

error in doc

there is a error in your doc
The import is
import Toast, {DURATION} from 'react-native-easy-toast'
instead of
import Toast, {DURATION} from 'react-native-toast-easy'

Not seeing any toast.

  return (
      <KeyboardAvoidingView
        style={styles.wrapper}
        enabled
        keyboardVerticalOffset={100}>
        <ScrollView contentContainerStyle={styles.container}>
          <Toast ref="toast" />
                 <BigButton
            buttonText="tap here!"
            onPress={this.showmytoast}
          />
        </ScrollView>
      </KeyboardAvoidingView>
    )
  }

showmytoast = () => {
this.refs.toast.show("Hello world", 500)

About Toast warning.

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

Please check the code for the Toast component.

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.