I want to remove a component in my React Native code, just like the "el.parentNode.removeChild(el)" in JavaScript or "[view removeFromSuperview]" in Objective-C, but I didn't see any related API in React documents. Is there any way to make it?
ReactJS componentWillUnmount() Method The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.
Use the useEffect hook to run a react hook when a component unmounts. The function we return from the useEffect hook gets invoked when the component unmounts and can be used for cleanup purposes. Copied!
componentWillUnmount. The componentWillUnmount method is called when the component is about to be removed from the DOM.
This article will demonstrate via examples how to resolve the How To Unmount Inactive Screens In Bottom Tab React Native error . You can unmount screens in bottom tab by adding option in navigation screenOptions: unmountOnBlur: true You can do it in Tab & Drawer Navigations but not in Stack Navigation.
In React Native or generally in React as I understand you normally don't remove components by calling 'remove[..]' but by changing the markup of the component thus changing the virtual DOM.
Here's some sample code that removes a MapView of a screen.
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
SwitchIOS,
MapView,
} = React;
var TestMap = React.createClass({
getInitialState() {
return {
showMap: true,
};
},
render: function() {
var map = this.state.showMap ? <MapView style={styles.map}/> : null;
return (
<View style={styles.container}>
<Text style={{marginBottom: 10}}>Remove a view in React Native</Text>
<SwitchIOS
onValueChange={(value) => this.setState({showMap: value})}
style={{marginBottom: 10}}
value={this.state.showMap}
/>
{map}
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
map: {
height: 200,
width: 300,
margin: 10,
borderWidth: 1,
borderColor: '#000000',
},
});
AppRegistry.registerComponent('TestMap', () => TestMap);
The relevant part being:
render: function() {
var map = this.state.showMap ? <MapView style={styles.map}/> : null;
return (
<View style={styles.container}>
[..]
{map}
</View>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With