4

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?

2 Answers 2

5

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>
      )
   }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why not just do {this.state.isFocused && <Text>Hello World</Text>}?
It's the same thing , I always extract variables from state and props before the return. It is just a convention.
2

You cannot reference refs from the render() method. Read more about the cautions of working with refs here.

As you can see in the image below, the first time the component mounts, refs is undefined, when I change the text (Which changes the State, which re-renders the component) refs is now available.

This app updates the state on text change of the Text Input and therefore re-renders the component with the proper refs

An optimal solution would be using state. I was going to post a solution but Freez already did. However, I am still posting this so you know why you should be using state instead of refs.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.