Alex
Alex

Reputation: 61

How do I remove a View in React Native

I am still quite new to react and till now I am still not able to understand how to remove a View when the user clicks on a specific button. For example lets say I have this block of code:

import React, { Component } from 'react'
import { AppRegistry, View, Text, TouchAbleOpacity } from 'react-native'

class Example extends Component {
    removeView(){
        // what should I do here?
    }

    render(){
        return (
            <View>
                <View> // View to be removed
                    <TouchAbleOpacity onPress={() => this.removeView()}>
                      <Text>Remove View</Text>
                    </TouchAbleOpacity>
                </View>
            </View>
        )
    }
}

AppRegistry.registerComponent('example', () => Example);

How do I programmatically remove the View element?

Upvotes: 4

Views: 9892

Answers (2)

Saleel
Saleel

Reputation: 899

Try something like this:

class Example extends Component {
    constructor(props) {
      super(props);
      this.state = {
        showView: true,
      }
    }

    removeView(){
       this.setState({
         showView: false,
       });
    }

    render(){
        return (
           <View style={{flex: 1, alignItems: 'center', justifyContent: 'center' }}>
           {this.state.showView && (
                <View style={{backgroundColor: 'red', height: 100, width: 100 }}> // View to be removed
                    <TouchableHighlight onPress={() => this.removeView()}>
                      <Text>Remove View</Text>
                    </TouchableHighlight>
                </View>
           )}
           </View>
        )
    }
}

Upvotes: 5

Lian van der Vyver
Lian van der Vyver

Reputation: 2184

I do it like this:

import React, { Component } from 'react'
import { AppRegistry, View, Text, TouchAbleOpacity } from 'react-native'

class Example extends Component {

    constructor() {
      super();
      this.state = {
        showView:true
      }
    }

    removeView(){
        this.setState({
          showView:false
        })
    }

    render(){
        return (
            <View>
                {this.renderView()}
            </View>
        )
    }

    renderView(){
      if(this.state.showView){
        return(
          <View>
              <TouchAbleOpacity onPress={() => this.removeView()}>
                <Text>Remove View</Text>
              </TouchAbleOpacity>
          </View>
        );
      }
    }
}

AppRegistry.registerComponent('example', () => Example);

Upvotes: 2

Related Questions