Search code examples
javascriptreactjsreact-nativepurely-functional

React Native conditionally render part of view while input is focused


I have the following scenario.

function MyComponent() {
  return (
    <View>
      <TextInput ref={ref => (this.input = ref)} style={styles.input} />
      {this.input.isFocused() && <Text>Hello World</Text>}
    </View>
  );
}

This actually works fine, but I get the warning:

MyComponent is accessing findNodeHandle inside its render. render should be a pure function.

How do I conditionally render The text block and avoid this warning?


Solution

  • You can use component state :

    class MyComponent extends React.Component {
    
       state = { isFocused: false }
    
       handleInputFocus = () => this.setState({ isFocused: true })
    
       handleInputBlur = () => this.setState({ isFocused: false })
    
       render() {
          const { isFocused } = this.state
    
          return (
            <View>
              <TextInput 
                onFocus={this.handleInputFocus} 
                onBlur={this.handleInputBlur} 
              />
              {isFocused && <Text>Hello World</Text>}
            </View>
          )
       }
    }