How to conditionally render a component without re-rendering the nested components?

Viewed 633

I'm trying to conditionally enable/disable this ScrollView when a button is pressed without it re-rendering the View and CardDeck nested inside of it. Any ideas? All help appreciated!

<>
  <ScrollView>
    <View >
        <CardDeck 
        infoStyles={handleInfoStyle}
        />
    </View>
  </ScrollView>
</>
3 Answers

you can only handle showing hiding any thing in your react app,when you update your state nor nothing will be changes, this state can be the opacity of a View or as below seting the some state and according to that show your code.

as an example:

const[state,setState]=useState(false);
<>
  <ScrollView>
<Button title='hello' onPress={()=>{setState(!state)}} />
    <View >
        {state && <CardDeck 
        infoStyles={handleInfoStyle}
        />}
    </View>
  </ScrollView>
</>

The CardDeck will be shown only when the state is true(after Clicking)

I came across this question when I needed to show/hide my custom keyboard (which has a ton of buttons) quickly. You can try something like

<View style={this.state.showScrollView? {top: 0, bottom: 0, left: 0, right: 0, position: "absolute"} : {overflow: "hidden"}}>
    <ScrollView>
        ...
    </ScrollView>
</View>

(You might need to make the scrollview pure with something like React.memo or PureComponent, and/or play around with the pointerEvents prop of the View to make things work.) But the idea is to toggle visibility at a higher level so your ScrollView can comfortably stay unchanged.

You can enable/disable scoll state using native props directly, which does not trigger any re-render anywhere.

 onButonPress = () => {
     this.scrollViewRef.setNativeProps({ scrollEnabled: false })
 }

 <ScrollView ref={ref => this.scrollViewRef = ref}>
     <View>
         <CardDeck 
             infoStyles={handleInfoStyle}
         />
     </View>
 </ScrollView>
Related