Search code examples
androidreactjsreact-nativeref

React Native - How can I use ref after deprecation?


I'm using ref to show a custom alert but I've got a warning about deprecation so how can I use ref or any replacement of that?

<MyAlert ref="alert" />

this.refs.alert.open(
        errorBody,
        [
            {
                text: pbtn, onPress: () => {
                    this._home_call()
                }
            },
            { text: nbtn, onPress: () => { } }
        ],
        {
            type: 'alert',
            cancelable: false,
        },
    );

react version: 16.13.1

react-native version: 0.63.2


Solution

  • for functional components

    use ref hook in react

    const alertRef = useRef(null);
    

    then use it like

    <MyAlert ref={alertRef />
    

    for class components

    create ref in constructor

    constructor() {
      super();
      this.alertRef= React.createRef();
     
    }
    

    then use it like

    <MyAlert ref={(ref) => this.alertRef = ref} />