Ravi Sharma
Ravi Sharma

Reputation: 527

How to write Custom flash message in react native

I want to display a custom message after successful record update when boolean value of recordUpdateSuccess become true and after 3seconds it should disappear.

{recordUpdateSuccess ? this.renderRecordUpdatedSucess() : null}

I have function to display message:

  renderRecordUpdatedSucess = () => (
    <View style={styles.sucessAlert}>
      <Text style={styles.sucessAlert}>Record updated successfully.</Text>
    </View>
  )

I tried to use setTimeout() to display message but not working. Any idea to acheive this one. I don't want to use Toast, any third party library for this one.

Upvotes: 0

Views: 7204

Answers (1)

Pramod
Pramod

Reputation: 1940

Custom flash message (No external Library) Working Example: https://snack.expo.io/@msbot01/1dcddc

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity  } from 'react-native';
import Constants from 'expo-constants';

// You can import from local files
import AssetExample from './components/AssetExample';

// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     flashMessage: false
    }
  }

  onPress(){
    this.setState({
      flashMessage: true
    },()=>{setTimeout(() => this.closeFlashMessage(), 3000)})
  }

  closeFlashMessage(){
    this.setState({
      flashMessage: false
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={()=>{this.onPress()}}>
          <Text>Click Me</Text>
        </TouchableOpacity >
        {this.state.flashMessage==true?
          <View style={styles.flashMessage}>
          <Text style={{color:'white'}}>This is custom Flash message</Text>
        </View>
        :
        null
        }

      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  flashMessage:{
    position:'absolute', 
    backgroundColor:'green', 
    width:'100%', 
    justifyContent:'center', 
    alignItems:'center',           
    height:40, 
    top:0
  }
});

Upvotes: 3

Related Questions