Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to know a component is on screen in ReactNative? like viewDidAppear or viewWillAppear

Tags:

react-native

If you're writing Swift you can use ViewController's life cycle hook, viewDidAppear or viewWillAppear to know whether specific View is on screen. Is there any way to do the similar thing in ReactNative? looks like no close one in the docs

like image 598
Dave Avatar asked Dec 31 '16 01:12

Dave


People also ask

How do I know if my screen is focused in react native?

React Navigation provides a hook that returns a boolean indicating whether the screen is focused or not. The hook will return true when the screen is focused and false when our component is no longer focused. This enables us to render something conditionally based on whether the user is on the screen or not.

How do you call a function when screen focus react native?

There are two approaches to calling an action on screen focusing: Using the withNavigationFocus higher order component provided by react-navigation. Listening to the 'didFocus' event with an event listener.


1 Answers

I don't think react native provides any functions which are called when you pop to previous view(unlike methods like componentWillMount() which is called when component mounts).

But I think you can pass a callback function when you navigate to new scene, and just before popping it call this function.

When you push a new component 'B' from 'A'

In Component A

callBackPop() {

 // manipulate state
}

pushNewScene() {
  this.props.navigator.push({name: 'B', callBack: this.callBackPop});
}

In Navigator

renderScene(route, navigator) {

  <B navigator={navigator} callback={route.callBack} />

}

In Component B

function popToPrevious() {
     this.props.callBack();

     this.props.navigator.pop();

}
like image 179
coder hacker Avatar answered Oct 06 '22 11:10

coder hacker