Search code examples
react-nativereact-props

React-Native: Passing keyword in props for searching


I need a little help in a small issue. In my first screen, I have a flatlist which has some keywords. I want if I click on any keyword, I should be navigated to another screen with the prop of that keyword. I am doing like this inside the flatlist:

<FlatList
    data={myRecentSearches}
    renderItem={({ item, index }) => (
    <TouchableOpacity
         onPress={() => props.navigation.navigate("search", { searchValue: `${item.keyword}` })}>
          <Text>{item.keyword}</Text>
    </TouchableOpacity>
)}

In the next screen, I want the input field should already be initialized with that keyword.

const SearchScreen = (props) => {
  const [searchValue, setSearchValue] = useState("");
  return (
    <View activeOpacity={0.5} style={styles.searchContainer}>
        <TextInput
          allowFontScaling={false}
          value={searchValue} //I want this value to be already initialized/populated with the prop
          returnKeyType="search"
          autoFocus
          />
      </View>
  )
}

Solution

  • In your first screen have the SearchScreen like this:

    return(
    <SearchScreen keyWord={item.keyword}/>
    )
    

    And inside SearchScreen:

    const SearchScreen = (props) => {
      const [searchValue, setSearchValue] = useState(props.keyWord);
      return (
        <View activeOpacity={0.5} style={styles.searchContainer}>
            <TextInput
              allowFontScaling={false}
              value={searchValue} //I want this value to be already initialized/populated with the prop
              returnKeyType="search"
              autoFocus
              />
          </View>
      )
    }