Mat
Mat

Reputation: 51

React Native - Add search bar in the header

I want to add a search button in the header on the right. When pressed, a search bar appears in the header.

I tried to use the setParams() function of react-navigation but I get an error.

My code :

    static navigationOptions = ({ navigation }) => {
        return {
            headerRight: (
                navigation.getParam('search') === 1 ?
                <TouchableOpacity onPress={navigation.getParam('searchBar')} style={{ marginHorizontal: 10 }}>
                    <FontAwesome name="search" size={28} color="white" />
                </TouchableOpacity>
                :
                <Text>My Search Bar</Text>
            )
        };
    };

    test() {
        this.props.navigation.setParams({searchBar: 0});
    }

    componentDidMount() {
        this.props.navigation.setParams({search: 1, searchBar: this.test})
    }

The code in the componentDidMount() function works. But not the one in the test function.

I get the following error message: undefined is not an object (evaluating 'this.props.navigation')

The result I wanted is that when I press the "Search" button, the text "Ok" appears

Upvotes: 0

Views: 6881

Answers (1)

hong developer
hong developer

Reputation: 13906

I think this is a simple error in the value of the change. You must change the search value to change the value you want.


      static navigationOptions = ({ navigation }) => {
        return {
           headerTitle: <LogoTitle />,
            headerRight: (
                navigation.getParam('search') === 1 ?
                <TouchableOpacity onPress={() => navigation.setParams({search: 0})} style={{ marginHorizontal: 10 }}>
                     <FontAwesome name="search" size={28} color="white" />
                </TouchableOpacity>
                :
                <Text>My Search Bar</Text>
            )
        };
    };

    componentDidMount() {
        this.props.navigation.setParams({search: 1, searchBar: this.test})
    }

Upvotes: 1

Related Questions