207

I'm really new to React Native and I'm wondering how can I hide/show a component.
Here's my test case:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight 
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>

I have a TextInput component, what I want is to show the TouchableHighlight when the input gets the focus, then hide the TouchableHighlight when the user press the cancel button.

I don´t know how to "access" the TouchableHighlight component in order to hide/show it inside of my functions showCancel/hideCancel.
Also, how can I hide the button from the very beginning?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Crysfel
  • 7,926
  • 3
  • 33
  • 41

30 Answers30

193

In your render function:

{ this.state.showTheThing && 
  <TextInput/>
}

Then just do:

this.setState({showTheThing: true})  // to show it  
this.setState({showTheThing: false}) // to hide it
muescha
  • 1,544
  • 2
  • 12
  • 22
Krishan Gupta
  • 3,586
  • 5
  • 22
  • 31
  • 2
    This worked for me. However, I'm not sure why when I do something like `{ this.state.showTheThing && (foo && bar)}` only "bar" is shown in the UI. I would expect "foo" and "bar" would be displayed. What I have needed to do to solve this is to call `{ this.state.showTheThing && (foo} { this.state.showTheThing && (bar}` – Tonatiuh Feb 09 '17 at 10:15
  • 3
    maybe this works? because the logical `&&` not combine elements `{ this.state.showTheThing && (foobar)}` – muescha Feb 21 '17 at 14:23
  • This worked for me , I wanted to show a "Next Step" button when a user uploaded their profilepicure . so my code was : ``{this.state.hasPic && }`` – Daggie Blanqx - Douglas Mwangi Feb 07 '19 at 09:01
  • 1
    For anyone struggling with showing more than one component, wrap your component with a fragment. eg. ```FooBar>``` – Ben Cull Oct 19 '19 at 23:32
153

I would do something like this:

var myComponent = React.createComponent({

    getInitialState: function () {
        return {
            showCancel: false,
        };
    },

    toggleCancel: function () {
        this.setState({
            showCancel: !this.state.showCancel
        });
    }

    _renderCancel: function () {
        if (this.state.showCancel) {
            return (
                <TouchableHighlight 
                    onPress={this.toggleCancel()}>
                    <View>
                        <Text style={styles.cancelButtonText}>Cancel</Text>
                    </View>
                </TouchableHighlight>
            );
        } else {
            return null;
        }
    },

    render: function () {
        return (
            <TextInput
                onFocus={this.toggleCancel()}
                onChangeText={(text) => this.doSearch({input: text})} />
            {this._renderCancel()}          
        );
    }

});
George Kagan
  • 5,913
  • 8
  • 46
  • 50
Mayank Patel
  • 2,787
  • 3
  • 13
  • 6
  • 1
    Thank you so much for this, just one small change that I needed to do: onFocus={() => this.showCancel() } this needs to be a callback function. – Crysfel May 15 '15 at 21:08
  • 4
    Only worked for me after changing the `return ''` to `return null` – k7k0 Feb 18 '16 at 22:02
  • 54
    You can also do `{someBoolVal && }` and it will only show if the bool value is true. – Nathan Hyland Jul 05 '16 at 20:18
  • This is the best answer – Kirill Husiatyn Dec 28 '16 at 16:32
  • 3
    I don't know this is the accepted answer which not implementing the original desired functionality show/hide, but instead add/remove – Muhammad Hamada Apr 16 '17 at 13:15
  • @KiritModi pls DONOT let return in a separate line alone . e.g. return \n (< TouchableHighlight > ...). js would return without jsx component as you expect. I am not sure if it's for you case but for me i spent more than 2 hours to find the issue (maybe stupid). – gonglong Aug 14 '17 at 13:51
  • also shorthand `{bool ? : }` – Leap Hawk Jan 30 '18 at 12:04
  • As per my understanding we are removing the component from memory. What if we that component is loaded with some data ? – Sujit Apr 27 '18 at 06:26
  • why is this better than the shorter answer?: { this.state.showTheThing && } – ox. May 15 '19 at 11:53
  • Just curious, what's the difference between a function call that has an underscore in its name? ("_renderCancel" vs "toggleCancel") – James Oct 25 '19 at 14:32
53

In react or react native the way component hide/show or add/remove does not work like in android or iOS. Most of us think there would be the similar strategy like

View.hide = true or parentView.addSubView(childView)

But the way react native work is completely different. The only way to achieve this kind of functionality is to include your component in your DOM or remove from DOM.

Here in this example I am going set the visibility of text view based on the button click.

enter image description here

The idea behind this task is the create a state variable called state having the initial value set to false when the button click event happens then it value toggles. Now we will use this state variable during the creation of component.

import renderIf from './renderIf'

class FetchSample extends Component {
  constructor(){
    super();
    this.state ={
      status:false
    }
  }

  toggleStatus(){
    this.setState({
      status:!this.state.status
    });
    console.log('toggle button handler: '+ this.state.status);
  }

  render() {
    return (
      <View style={styles.container}>
        {renderIf(this.state.status)(
          <Text style={styles.welcome}>
            I am dynamic text View
          </Text>
        )}

        <TouchableHighlight onPress={()=>this.toggleStatus()}>
          <Text>
            touchme
          </Text>
        </TouchableHighlight>
      </View>
    );
  }
}

the only one thing to notice in this snippet is renderIf which is actually a function which will return the component passed to it based on the boolean value passed to it.

renderIf(predicate)(element)

renderif.js

'use strict';
const isFunction = input => typeof input === 'function';
export default predicate => elemOrThunk =>
  predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;
Nissa
  • 4,636
  • 8
  • 29
  • 37
Rajan Twanabashu
  • 4,586
  • 5
  • 43
  • 55
36

React Native's layout has the display property support, similar to CSS. Possible values: none and flex (default). https://facebook.github.io/react-native/docs/layout-props#display

<View style={{display: 'none'}}> </View>
Estevão Lucas
  • 4,440
  • 34
  • 37
  • 3
    Careful not to use this with `position: absolute`, it doesn't actually hide it! Known bug from 0.54 - 0.59 (at least): https://github.com/facebook/react-native/issues/18415 – Joshua Pinter Jul 19 '19 at 00:50
  • 1
    This is the answer that applied to my situation, which was having to press a hidden button programatically. I don't think many of the other solutions would have worked for my specific problem, as if the button's not rendered, it can't be clicked. – Jay Jan 09 '22 at 22:45
24

in render() you can conditionally show the JSX or return null as in:

render(){
    return({yourCondition ? <yourComponent /> : null});
}
Asinox
  • 6,747
  • 14
  • 61
  • 89
Mar
  • 241
  • 2
  • 3
20

Most of the time i'm doing something like this :

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isHidden: false};
    this.onPress = this.onPress.bind(this);
  }
  onPress() {
    this.setState({isHidden: !this.state.isHidden})
  }
  render() {
    return (
      <View style={styles.myStyle}>

        {this.state.isHidden ? <ToHideAndShowComponent/> : null}

        <Button title={this.state.isHidden ? "SHOW" : "HIDE"} onPress={this.onPress} />
      </View>
    );
  }
}

If you're kind of new to programming, this line must be strange to you :

{this.state.isHidden ? <ToHideAndShowComponent/> : null}

This line is equivalent to

if (this.state.isHidden)
{
  return ( <ToHideAndShowComponent/> );
}
else
{
  return null;
}

But you can't write an if/else condition in JSX content (e.g. the return() part of a render function) so you'll have to use this notation.

This little trick can be very useful in many cases and I suggest you to use it in your developments because you can quickly check a condition.

Regards,

EDIT: For a more straight forward synthax, you can do {this.state.isHidden && <ToHideAndShowComponent/>}. Here, the left operand is evaluated before the right one, so if isHidden is false, then the component will not show up.

KuroAku
  • 235
  • 1
  • 3
  • 7
13

just use

style={ width:0, height:0 } // to hide
amos
  • 187
  • 1
  • 2
  • 4
    It would be helpful if you add some context / detail to the answer. – UditS Feb 07 '16 at 17:01
  • Assuming you have a mechanism to decide which component to hide, this answer is quite useful. You can wrap whatever component you are trying to hide with a View with style={{width:0, height:0}}. – Josh Baker May 25 '16 at 23:55
  • 6
    how do you restore the element to the original width and height? – Some Juan Jul 26 '16 at 06:44
  • 4
    don't understand why is this downvoted, but in many case it is good advice. I need to switch between animated and non-animated gif. Conditional switching img caused delays with no img at screen. As part of fix, I'm displaying both img, but the one who should be hidden has zero width and height. – mauron85 Sep 12 '16 at 17:57
  • This keeps the component in memory, which can be a problem with big components. Why not use the great examples above? They insert and remove component completely... – A-S Nov 05 '16 at 12:23
  • In most cases, I agree use a conditional to add or remove a component from you View. However, there are cases such as an overlay which will sit on top of it's siblings, blocking the UI, unless given a height of 0. I ran into this issue when using this module: https://github.com/eyaleizenberg/react-native-custom-action-sheet – AndrewHenderson Apr 30 '17 at 06:43
  • {width:0} or {height:0} is enough – nazar kuliyev Dec 28 '17 at 10:11
13

I needed to switch between two images. With conditional switching between them there was 5sec delay with no image displayed.

I'm using approach from downvoted amos answer. Posting as new answer because it's hard to put code into comment with proper formatting.

Render function:

<View style={styles.logoWrapper}>
  <Image
    style={[styles.logo, loading ? styles.hidden : {}]}
    source={require('./logo.png')} />
  <Image
    style={[styles.logo, loading ? {} : styles.hidden]}
    source={require('./logo_spin.gif')} />
</View>

Styles:

var styles = StyleSheet.create({
  logo: {
    width: 200,
    height: 200,
  },
  hidden: {
    width: 0,
    height: 0,
  },
});

screencast

mauron85
  • 1,364
  • 1
  • 14
  • 28
  • This keeps the components in memory, which can be a problem with big components. Why not use the great examples above? They will insert the right picture and remove the other one completely... – A-S Nov 05 '16 at 12:23
  • 4
    any of those examples doesn't work properly when you try to create animated spinner. Like I already mentioned in my answer on android trying to switch img for anim gif, will cause 5s delay when no png nor gif is shown. I believe the delay is caused by loading gif into memory, which might take some time. However iOS seems to do much better job here. If you don't believe me, try it yourself. – mauron85 Nov 05 '16 at 13:23
  • 1
    Of course as pointed out it's not optimal solution for every component. But IMHO for loading spinner it's just fine. It will eventually be unloaded when user transition to another page. – mauron85 Nov 05 '16 at 13:30
13

enter image description here

Hide And Show parent view of Activity Indicator

constructor(props) {
  super(props)

  this.state = {
    isHidden: false
  }  
} 

Hide and Show as Follow

{
   this.state.isHidden ?  <View style={style.activityContainer} hide={false}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
}

Full reference

render() {
    return (
       <View style={style.mainViewStyle}>
          <View style={style.signinStyle}>
           <TextField placeholder='First Name' keyboardType='default' onChangeFirstName={(text) => this.setState({firstName: text.text})}/>
           <TextField placeholder='Last Name' keyboardType='default' onChangeFirstName={(text) => this.setState({lastName: text.text})}/>
           <TextField placeholder='Email' keyboardType='email-address' onChangeFirstName={(text) => this.setState({email: text.text})}/>
           <TextField placeholder='Phone Number' keyboardType='phone-pad' onChangeFirstName={(text) => this.setState({phone: text.text})}/>
           <TextField placeholder='Password' secureTextEntry={true} keyboardType='default' onChangeFirstName={(text) => this.setState({password: text.text})}/>
           <Button  style={AppStyleSheet.buttonStyle} title='Sign up' onPress={() => this.onSignupPress()} color='red' backgroundColor='black'/>
          </View>
          {
            this.state.isHidden ?  <View style={style.activityContainer}><ActivityIndicator size="small" color="#00ff00" animating={true}/></View> : null
          }
      </View>
   );
}

On Button presss set state as follow

onSignupPress() {
  this.setState({isHidden: true})
}

When you need to hide

this.setState({isHidden: false})
Harshal Valanda
  • 5,331
  • 26
  • 63
7

I had the same issue where I would want to show / hide Views, but I really didn't want the UI jumping around when things were added/removed or necessarily to deal with re-rendering.

I wrote a simple Component to deal with it for me. Animated by default, but easy to toggle. I put it on GitHub and NPM with a readme, but all the code is below.

npm install --save react-native-hideable-view

import React, { Component, PropTypes } from 'react';
import { Animated  } from 'react-native';

class HideableView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      opacity: new Animated.Value(this.props.visible ? 1 : 0)
    }
  }

  animate(show) {
    const duration = this.props.duration ? parseInt(this.props.duration) : 500;
    Animated.timing(
      this.state.opacity, {
        toValue: show ? 1 : 0,
        duration: !this.props.noAnimation ? duration : 0
      }
    ).start();
  }

  shouldComponentUpdate(nextProps) {
    return this.props.visible !== nextProps.visible;
  }

  componentWillUpdate(nextProps, nextState) {
    if (this.props.visible !== nextProps.visible) {
      this.animate(nextProps.visible);
    }
  }

  render() {
    if (this.props.removeWhenHidden) {
      return (this.visible && this.props.children);
    }
    return (
      <Animated.View style={{opacity: this.state.opacity}}>
        {this.props.children}
      </Animated.View>
    )
  }
}

HideableView.propTypes = {
  visible: PropTypes.bool.isRequired,
  duration: PropTypes.number,
  removeWhenHidden: PropTypes.bool,
  noAnimation: PropTypes.bool
}

export default HideableView;
Tonithy
  • 2,300
  • 1
  • 20
  • 20
  • Nice one, just what I was looking for :) – Adamski Jul 19 '17 at 09:03
  • This works best, and behaves like a proper view when you put other components that have a lifecycle inside the view (which doesn't work with `visible && (...)`. – dB. Jul 01 '18 at 23:56
6

An additional option is to apply absolute positioning via styling, setting the hidden component in out-of-screen coordinates:

<TextInput
    onFocus={this.showCancel()}
    onChangeText={(text) => this.doSearch({input: text})}
    style={this.state.hide ? {position: 'absolute', top: -200} : {}}
/>

Unlike in some of the previous suggestions, this would hide your component from view BUT will also render it (keep it in the DOM), thus making it truly invisible.

d4vidi
  • 2,407
  • 26
  • 27
  • 2
    This idea suits for me, thanks. If anybody needs, look at it too: https://gist.github.com/jaysoo/cbb81a07cc22015a72e9 – Chaki_Black Nov 06 '17 at 10:51
6
constructor(props) {
    super(props);
    this.state = {
      visible: true,
}
}

declare visible false so by default modal / view are hide

example = () => {

 this.setState({ visible: !this.state.visible })

}

**Function call **

{this.state.visible == false ?
        <View>
            <TouchableOpacity
              onPress= {() => this.example()}>   // call function
                          <Text>
                            show view
                          </Text>
            </TouchableOpacity>

</View>
:
 <View>
    <TouchableOpacity
              onPress= {() => this.example()}>
                          <Text>
                            hide view
                          </Text>
            </TouchableOpacity>
</View> 
 }
Shivo'ham 0
  • 1,333
  • 11
  • 19
6

Three ways to show\hide components:

- Class Component: / ------------------------------------------------------------------------------------------------------------

in all examples i used below state:

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

1. using display prop

<View display={this.state.showComponent ? 'flex' : 'none'} /> 

2. using display prop with style

<View style={{display:this.state.showComponent ? 'flex' : 'none'}} />

3. limit render

{
    this.state.showComponent &&
    <View /> // Or <View> ... </View>
}


- Functional Component:/ ------------------------------------------------------------------------------------------------------------

in all examples i used below state:

const [showComponent, setShowComponent] = useState(true);

1. using display prop

<View display={showComponent ? 'flex' : 'none'} /> 

2. using display prop with style

<View style={{showComponent  ? 'flex' : 'none'}} />

3. limit render

{
    showComponent &&
    <View /> // Or <View> ... </View>
}
Arash Younesi
  • 1,671
  • 1
  • 14
  • 23
5

If you need the component to remain loaded but hidden you can set the opacity to 0. (I needed this for expo camera for instance)

//in constructor    
this.state = {opacity: 100}

/in component
style = {{opacity: this.state.opacity}}

//when you want to hide
this.setState({opacity: 0})
4

I usually use something like this

const [showComponent, setShowComponent] = useState(false)
return(
    <div>
         {showComponent && (<Text>Hello</Text>)}
         <Button onPress={() => {setShowComponent(true)}}>Click me</Button>
    </div>
)

It will show 'Hello' once the button is pressed. This is called conditional rendering. You can refer to w3schools to learn about conditional rendering.

  • corrected the useState syntax via Edit answer option. Any trusted community member kindly approve the edit. It's the best solution I was looking for and worked for me. – Fahad Ali Qureshi Jun 07 '22 at 05:05
3
// You can use a state to control wether the component is showing or not
const [show, setShow] = useState(false); // By default won't show

// In return(
{
    show && <ComponentName />
}

/* Use this to toggle the state, this could be in a function in the 
main javascript or could be triggered by an onPress */

show == true ? setShow(false) : setShow(true)

// Example:
const triggerComponent = () => {
    show == true ? setShow(false) : setShow(true)
}

// Or
<SomeComponent onPress={() => {show == true ? setShow(false) : setShow(true)}}/>

Oyebola
  • 141
  • 4
  • 3
    While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf May 31 '20 at 20:26
  • 1
    Updated, explained a bit more. Hope it helps! – Oyebola Jun 01 '20 at 11:12
2

You can use my module react-native-display to show/hide components.

2

The following example is coding in typescript with Hooks.

import React, { useState, useEffect } from "react";

........

const App = () => {

   const [showScrollView, setShowScrollView] = useState(false);

   ......

   const onPress = () => {
    // toggle true or false
    setShowScrollView(!showScrollView);
  }

  ......

      </MapboxGL.ShapeSource>
        <View>{showScrollView ? (<DetailsScrollView />) : null}</View>
      </MapboxGL.MapView>
  ......

}
madeinQuant
  • 1,721
  • 1
  • 18
  • 29
2

I would vouch for using the opacity-method if you do not want to remove the component from your page, e.g. hiding a WebView.

<WebView
   style={{opacity: 0}} // Hide component
   source={{uri: 'https://www.google.com/'}}
 />

This is useful if you need to submit a form to a 3rd party website.

user2210411
  • 1,497
  • 1
  • 9
  • 7
1

i am just using below method to hide or view a button. hope it will help you. just updating status and adding hide css is enough for me

constructor(props) {
   super(props);
      this.state = {
      visibleStatus: false
   };
}
updateStatusOfVisibility () {
   this.setStatus({
      visibleStatus: true
   });
}
hideCancel() {
   this.setStatus({visibleStatus: false});
}

render(){
   return(
    <View>
        <TextInput
            onFocus={this.showCancel()}
            onChangeText={(text) => {this.doSearch({input: text}); this.updateStatusOfVisibility()}} />

         <TouchableHighlight style={this.state.visibleStatus ? null : { display: "none" }}
             onPress={this.hideCancel()}>
            <View>
                <Text style={styles.cancelButtonText}>Cancel</Text>
            </View>
        </TouchableHighlight>
     </View>)
}
Kiran Chenna
  • 1,562
  • 1
  • 11
  • 9
1

Actually, in iOS development by react-native when I use display: 'none' or something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 0,
    height: 0
  }
});

The iOS doesn't load anything else of the Image component like onLoad or etc, so I decided to use something like below:

const styles = StyleSheet.create({
  disappearImage: {
    width: 1,
    height: 1,
    position: 'absolute',
    top: -9000,
    opacity: 0
  }
});
1

If you want to hide it but keep the space occupied by the component like css's visibility: hidden setting in the component's style opacity: 0 should do the trick.

Depending on the component other steps in disabling the functionality might be required as interaction with an invisible item is possible.

Gabriel P.
  • 3,400
  • 2
  • 32
  • 23
1

We now have hooks so I would recommend a reformat. Use hooks to turn components on/off.

const [modalVisible, setModalVisible] = setState(false);

Then have a button

<Button title="Press Me" onPress={() => {
   setModalVisible(true);
}}

Then, inside your return statement

return(
<View>
    {modalVisible &&
   Insert modal code in here.
}
</View>
)
Evan Erickson
  • 471
  • 5
  • 12
1

You can do it, using the useState Hook

The useState basically, is a feature which helps us preserve the values of variables even after multiple re-renders.

It acts a local state management tool, for storing values, after the component renders or re-renders.

In addition, to that you can also, trigger it to update the UI, by changing the value of the state variable.

const [show,setShow] = useState(true)

So, here we have destructured the, values that useState sends, first is the variable, through which we can get the value, and the second is a function through which we can update the state variables value.

So, in your case -

import React, {useState} from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import Constants from 'expo-constants';

export default function App() {
const [show,setShow] = useState(true)
return (
 <View style={styles.container}>
   {show && <Text style={styles.paragraph}>
     Showing and Hiding using useState
   </Text>}
    <Button
     title="Press me"
     onPress={() => {setShow(!show)}}
   />
 </View>
);
}

const styles = StyleSheet.create({
container: {
 flex: 1,
 justifyContent: 'center',
 paddingTop: Constants.statusBarHeight,
 backgroundColor: '#ecf0f1',
 padding: 8,
},
paragraph: {
 margin: 24,
 fontSize: 18,
 fontWeight: 'bold',
 textAlign: 'center',
},
});

In this example, on Button press, we are toggling the state variable from true to false.

You can show or hide JSX Code, using boolean conditions, which we are doing in this statement.

{show && <Text style={styles.paragraph}>
     Showing and Hiding using useState
   </Text>}

This is an quick and effective method of using state for UI manipulations.

A . L. I
  • 191
  • 1
  • 7
0

Very Easy. Just change to () => this.showCancel() like below:

<TextInput
        onFocus={() => this.showCancel() }
        onChangeText={(text) => this.doSearch({input: text})} />

<TouchableHighlight 
    onPress={this.hideCancel()}>
    <View>
        <Text style={styles.cancelButtonText}>Cancel</Text>
    </View>
</TouchableHighlight>
Lim Neo
  • 75
  • 8
0

The only way to show or hide a component in react native is checking a value of a parameter of app state like state or props. I provided a complete example as below:

import React, {Component} from 'react';
import {View,Text,TextInput,TouchableHighlight} from 'react-native'

class App extends Component {

    constructor(props){
        super(props);
        this.state={
            show:false
        }
}

    showCancel=()=>{
        this.setState({show:true})
    };

    hideCancel=()=>{
        this.setState({show:false})
    };

    renderTouchableHighlight(){
        if(this.state.show){
           return(
               <TouchableHighlight
                   style={{borderColor:'black',borderWidth:1,marginTop:20}}
                   onPress={this.hideCancel}>
                   <View>
                       <Text>Cancel</Text>
                   </View>
               </TouchableHighlight>
           )
        }
        return null;
    }

    render() {


        return (
            <View style={{justifyContent:'center',alignItems:'center',flex:1}}>
                <TextInput
                    style={{borderColor:'black',borderBottomWidth:1}}
                    onFocus={this.showCancel}
                />
                {this.renderTouchableHighlight()}

            </View>
        );
    }
}

export default App;

Here is the result

Meisam Nazari
  • 904
  • 10
  • 18
0

You can use the conditions for show and hide the components

constructor(){

    super();

    this.state ={

      isVisible:true

    }
  }

  ToggleFunction = () => {

    this.setState(state => ({

      isVisible: !state.isVisible

    }));

  };

  render() {
  
    return (

      <View style={styles.MainContainer}>

      {

        this.state.isVisible ? <Text style= {{ fontSize: 20, color: "red", textAlign: 'center' }}> Hello World! </Text> : null
      }

      <Button title="Toggle Visibility" onPress={this.ToggleFunction} />

      </View>
    );
  }
0

I solve this problem like this:

<View style={{ display: stateLoad ? 'none' : undefined }} />

0

Just simply use this because I wanted to use the "useRef" conditions were not an option for me. You can use this suppose when you want to use useRef hook and press the button.

   <Button
      ref={uploadbtn}
      buttonStyle={{ width: 0, height: 0, opacity: 0, display: "none" }}
      onPress={pickImage}
    />
Sehrish Waheed
  • 1,230
  • 14
  • 17
-2
checkincheckout = () => {
        this.setState({ visible: !this.state.visible })
}

render() {
        return (
{this.state.visible == false ?
        <View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>

        <View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>

            <TouchableOpacity onPress={() => this.checkincheckout()}>

                <Text style={{ color: 'white' }}>Click to Check in</Text>

            </TouchableOpacity>

        </View>

    </View>
:
<View style={{ alignItems: 'center', flexDirection: 'row', marginTop: 50 }}>

<View style={{ flex: 1, alignItems: 'center', flexDirection: 'column' }}>

   <TouchableOpacity onPress={() => this.checkincheckout()}>

        <Text style={{ color: 'white' }}>Click to Check out</Text>

    </TouchableOpacity>

</View>

</View>
 }

);
}

thats all. enjoy your coding...

Mahendren Mahisha
  • 1,072
  • 11
  • 9