Skip to content

Cannot use state inside of header #10286

@tamis-laan

Description

@tamis-laan

Current behavior

I'm adding a search bar into the components header. The search bar uses the search state and changes the search term onChangeText:

const [search, setSearch] = useState('')
useEffect(()=>{
          navigation?.setOptions({
	          header:() => (
			          <SearchBar 
				          placeholder='search'
				          value={search}
				          onChangeText={text => {
					          setSearch(text)
				          }}
			          />
                                )
          })
},[])

Expected behavior

I would expect setSearch to work and change the value of search when onChangeText is triggered.

However this is not the case the search text stays the same.

Reproduction

https://snack.expo.dev/hfFh3wP-J

Platform

  • Android
  • iOS
  • Web
  • Windows
  • MacOS

Packages

  • @react-navigation/bottom-tabs
  • @react-navigation/drawer
  • @react-navigation/material-bottom-tabs
  • @react-navigation/material-top-tabs
  • @react-navigation/stack
  • @react-navigation/native-stack

Environment

  • [] I've removed the packages that I don't use
package version
@react-navigation/native
@react-navigation/bottom-tabs
@react-navigation/drawer
@react-navigation/material-bottom-tabs
@react-navigation/material-top-tabs
@react-navigation/stack
@react-navigation/native-stack
react-native-safe-area-context
react-native-screens
react-native-gesture-handler
react-native-reanimated
react-native-tab-view
react-native-pager-view
react-native
expo
node
npm or yarn

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions