1

I want to display something in my react component when user clicks into a text input (something similar to Instagram's search, where if you click on their input field, a search component suggestion shows up.

const SearchScreen = props => {

  const renderSearch = () => {
    return (
      <>
       // need to display the search suggestion
      </>
    )
  }

  return (
    <>
      <TextInput
        placeholder="Search"
        onChangeText={text => handleChange(text)}
        value={searchText}
        onFocus={() => renderSearch()} // based on focus, then render component
      />
      <View>
        // how do I render here?
        // this will render on load, but need to render onFocus
        {renderSearch}
      </View>
    </>
  );
};
4
  • 1
    You can apply a similar pattern than stackoverflow.com/a/34091564/1839692. For instance you can use an const [searchFocus, setSearchFocus] = useState(false) to display (or not) your component and set this value accordingly in your onFocus, onBlur events. Commented Mar 27, 2020 at 16:58
  • Does this answer your question? Focus style for TextInput in react-native Commented Mar 27, 2020 at 16:59
  • Ah got it! yeah it did, thank you! do you want to answer the question? perhaps write a snippet so I can approve? Commented Mar 27, 2020 at 17:46
  • Done. Hope it will work. Commented Mar 27, 2020 at 21:08

1 Answer 1

1

You can apply a similar pattern than stackoverflow.com/a/34091564/1839692.

For instance you can try something like :

const SearchScreen = props => {
  const [searchFocus, setSearchFocus] = useState(false)

  const renderSearch = () => {
    return (
      <>
       // need to display the search suggestion
      </>
    )
  }

  return (
    <>
      <TextInput
        placeholder="Search"
        onChangeText={text => handleChange(text)}
        value={searchText}
        onFocus={() => setSearchFocus(true)}
        onBlur={() => setSearchFocus(false)}
      />
      { searchFocus 
        ? <View>
            {renderSearch}
          </View> 
        : <View>
            // Add here the code to display when not searching
          </View>
      }

    </>
  );
};
Sign up to request clarification or add additional context in comments.

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.