Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call React Native custom alert as a function?

I'm developing a React Native app. I created my own custom alert as a component using modal. When I use it, I always need to add my alert component in my render() function.

Is there any way to use the custom alert without rendering it inside my render() function?

I mean, I can use Alert in react-native by calling it as Alert.alert(). I want to use my own custom alert also like that.

How can I do that?

like image 759
Sennen Randika Avatar asked Oct 27 '25 02:10

Sennen Randika


1 Answers

You could do this

class SomeComponent extends Component {
  static myComponentInstance

  constructor(props) {
    super(props)

    this.state = {
      visible: false,
      text: ""
    }

    SomeComponent.myComponentInstance = this
  }

  static show(text) {
    SomeComponent.myComponentInstance._show(text)
  }


  _show(text) {
    this.setState({ visible: true, text })
  }

  render(){
    return (
      <Modal visible={this.state.visible}>
        <Text>{this.state.text}</Text>
      </Modal>
    )
  }
}

const AppRoot = () => (
  <View>
    <Navigator />
    <SomeComponent/>
  </View>
)

And to show it you can do anywhere SomeComponent.show("some text")

like image 140
sniib Avatar answered Oct 28 '25 17:10

sniib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!