Toast.js 2.9 KB
'use strict';

import React, {Component} from 'react'
import {
    StyleSheet,
    View,
    Text,
    Dimensions,
    ActivityIndicator,
    Platform,
} from 'react-native';

import TimerMixin from 'react-timer-mixin';

export default class Toast extends Component {

    static propTypes = {
        isVisible: React.PropTypes.bool.isRequired,
        size: React.PropTypes.string,
        color: React.PropTypes.string,
        overlayWidth: React.PropTypes.number,
        overlayHeight: React.PropTypes.number,
        overlayColor: React.PropTypes.string,
        text: React.PropTypes.string,
        textColor: React.PropTypes.string,
        textFontSize: React.PropTypes.number,
    };

    static defaultProps = {
        isDismissible: false,
        overlayWidth: 100,
        overlayHeight: 50,
        overlayColor: 'rgba(0,0,0,0.6)',
        size: (Platform.OS === 'ios') ? 'large' : 'small',
        color: (Platform.OS === 'ios') ? 'white' : 'gray',
        text: '...',
        textColor: '#eeeeee',
        textFontSize: 14,
    };

    constructor(props) {
        super(props);
        // this.show = this.show.bind(this);
    
        this.state = {
            isVisible: this.props.isVisible,
        };
    }

    // show(){
    //     this.setState({isVisible: true,});
    //     this.timer = TimerMixin.setTimeout(() => {
    //         this.setState({
    //             isVisible: false,
    //         });  
    //     }, 3000);
    // }


    componentWillUnmount() {
        this.timer && TimerMixin.clearTimeout(this.timer);
    }

    render() {

        if (!this.state.isVisible) {
            return null;
        }
        else{
            this.timer = TimerMixin.setTimeout(() => {
            this.setState({
                isVisible: false,
            });  
        }, 3000);
        }

        let customStyles = StyleSheet.create({
            overlay: {
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: 10,
                backgroundColor: this.props.overlayColor,
                width: this.props.overlayWidth,
                height: this.props.overlayHeight,
            },
            text: {
                color: this.props.textColor,
                fontSize: this.props.textFontSize,
            },
        });

        return (
            <View style={styles.container}>
                <View style={customStyles.overlay}>
                    <Text style={customStyles.text}>{this.props.text}</Text>
                </View>
            </View>
        );
    }
}

let {width, height} = Dimensions.get('window');
let navbarHeight = (Platform.OS === 'android') ? 50 : 64;

const styles = StyleSheet.create({
    container: {
        position: 'absolute',
        backgroundColor: 'transparent',
        justifyContent: 'center',
        alignItems: 'center',
        top: -navbarHeight,
        bottom: 0,
        left: 0,
        right: 0,
    },
});