Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access component state inside navigation options in react native?

Tags:

react-native

I want to access my component state inside navigationOptions. I tried to assign it to params inside componentDidMount. Still it didn't work. How can I set, this.state.SearchText as the value of the input which is inside navigationOptions?

export default class WorkoutScreen extends Component {
  constructor(props) {
    super(props);

    this.state = {
      searchText: "Test Text"
    };
  }

  componentDidMount() {
    this.props.navigation.setParams({
      searchWorkouts: this.searchWorkoutHandler
    });
  }

  onChangeSearch = value => {
    this.setState({
      searchText: value
    });
  };

  searchWorkoutHandler = () => {
    alert("Searching Workouts");
  };

  render() {
    return (
      <View>
        <Text style={styles.searchInput}>{this.state.searchText}</Text>
      </View>
    );
  }

  static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    alert(params.searchText);

    return {
      headerTitle: (
        <SearchInput
          style={styles.searchInput}
          value={params.searchText}
          source={Search}
          borderRadius={50}
          placeholder="Search / Filter"
          onChangeText={value => this.onChangeSearch(value)}
          onPress={() => params.searchWorkouts()}
        />
      ),
      headerTitleStyle: { width: "100%", alignItems: "center" },
      headerStyle: {
        paddingRight: 10,
        paddingLeft: 10
      },
      headerLeft: (
        <ClickableIcon
          source={Bookmark}
          onIconPressed={() => alert("Notifications Clicked Workout")}
        />
      ),
      headerRight: (
        <ClickableIcon
          source={Movements}
          onIconPressed={() => alert("Add New Clicked")}
        />
      )
    };
  };
}

Is there any standard way that I can use to achieve this?

like image 658
Shashika Avatar asked May 08 '18 14:05

Shashika


1 Answers

You'd need to call this.props.navigation.setParams whenever the state changes to update the params value in navigationOptions:

componentDidMount() {
  this.props.navigation.setParams({
    searchWorkouts: this.searchWorkoutHandler,
    searchText: this.state.searchText,
  });
}

onChangeSearch = (value) => {
  this.setState({
    searchText: value,
  });
  this.props.navigation.setParams({
    searchText: value,
  });
};
like image 128
Roy Wang Avatar answered Oct 07 '22 00:10

Roy Wang