Skip to content
Advertisement

i am failing to access a func in my child component

the are about three more components between this one and the one i want it to function in, so i keep on passing it down as a prop till i get to the component i want. it is supposed to run when the user clicks a button but i get an error that this.props.route.params.ToggleFavorites is not a function please help!!!!

 constructor(props){
    super(props)
    this.state = {
      hymnNumber: '',
      favorites: []
    }
  }

  Sort = () => {
    let x = [...this.state.favorites] 
    for(let i=0; i<x.length-1;i++){
      if(parseInt(x[i+1].slice(0,2)) < parseInt(x[i].slice(0,2))){
        let y = x[i]
        x[i] = x[i+1]
        x[i+1] = y
        this.Sort()
      }
    }
    this.setState({favorites: [...x]})
  }

  ToggleFavorites = (id) =>{
    const item = ContentData.filter(item => item.slice(0, 2) === id)
    let arr = [...this.state.favorites]

    if(arr.includes(item[0]) === false){
      arr = [...arr, ...item]
    }else{
      arr = arr.filter(favorite => favorite === item[0])
    }
    this.setState({favorites: [...arr]})
    this.Sort()
  }
  clearAll = () =>{
    this.setState({favorites: []})
  }

  render(){
    return (     
        <View>
          <Pressable style={styles.buttonStyles} onPress = {() => this.props.navigation.push('Favorites', {favorites: this.state.favorites, clearAll: this.clearAll})}>
            <Text style={styles.buttonText}>favorites</Text>
          </Pressable>
          <Pressable style={styles.buttonStyles} onPress={() => this.props.navigation.push('Search', {favorites: this.state.favorites, ToggleFavorites: this.ToggleFavorites})}>
)}}```

Advertisement

Answer

If you’re passing it down as a prop, it won’t be in the route params, it will just be in the props at the top level (i.e. this.props.ToggleFavorites). The route params are only populated by navigation (i.e. when you call navigation.navigate('screen', {data: 'hi'}), you’ll get {data: 'hi'} in this.props.route.params).

Instead of passing the function down so many levels, consider using composition instead. When used properly, this pattern will eliminate boilerplate and reduce error surface area. https://plainenglish.io/blog/how-to-avoid-prop-drilling-in-react-using-component-composition

Another option is to store the function in a Context, although that has more caveats and should be used with care. https://reactjs.org/docs/context.html

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement