Orhan Esin
Orhan Esin

Reputation: 46

How to handle searchbar onchangetext event from navigation in react-native?

I want to make a search activity in react-native. I create a stacknavigation in tabBottomNavigator and stacknavigation has navigation options and headerLeft options. I have , and components. My question is about how to handle searchbar onchangetext event from component even it is in a diffrent class. Thanks...

StackForSearch.js

export default createStackNavigator({ Search:{ screen: Search,
navigationOptions: ({ navigation }) =>({
  headerLeft: <SearchHeader navigation={navigation}/>,
  }),
},});

SearchHeader.js

export default class SearchHeader extends Component<{}>{


  render(){

    return(
      <View style={styles.Container} >
      <SearchBar
        containerStyle={{backgroundColor:'white', margin:0,padding:0,borderWidth:0,borderBottomWidth:0}}
        inputStyle={{backgroundColor: 'white',paddingLeft:36,fontSize:16,color:'#171F33'}}
        lightTheme
        round
        onChangeText={}
        icon={{style:{color:'black', fontSize:22 ,margin:0}}}
        placeholder='Search..' />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  Container:{
    flex:1
  }
});

Search.js - I want to handle the onChangeText event in Search.js

export default class Search extends Component<{}>{

  constructor(props){
    super(props);
  }

  render(){

    return(
      <View style={styles.Container}>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  Container:{
    flex:1,
  },
  StatusBar:{
    marginTop: Platform.OS === 'ios' ? 0 : Constants.statusBarHeight,
    backgroundColor:'#171F33'
  }
});

Upvotes: 0

Views: 1764

Answers (1)

Helmer Barcos
Helmer Barcos

Reputation: 2076

The function onChangeText from SearchBar on your SearchHeader.js get fired everytime the Text changes. so you could pass to onChangeText property another function that is passed from Search.js as a props.

  1. Add onChangeText={this.props.onChangeText} in your SearchHeader.js
  2. Create an arrow function in your Search.js and pass it as a props to the SearchHeader.js component:

     export default class Search extends Component<{}>{    
       constructor(props){
         super(props);
       }
    
       onChangeText = (newText) => {
         //your custom logic here
         console.log(newText);
       }
    
       render(){    
        return(
         <View style={styles.Container}>
          <SearchHeader 
            onChangeText={this.onChangeText}
          />
         </View>
        );
       }
     }
    
     const styles = StyleSheet.create({
       Container:{
        flex:1,
       },
      StatusBar:{
       marginTop: Platform.OS === 'ios' ? 0 : Constants.statusBarHeight,
       backgroundColor:'#171F33'
      }
    });
    

Upvotes: 1

Related Questions