BoJack
BoJack

Reputation: 325

What is causing the React not a function error?

I'm trying to pass a state from a child to a parent using class based components. Why do I keep getting the this.props.onSortSelect is not a function? I have tried decoding similar questions but can't come to a fix. Thanks in advance.

Child:

class Sort extends React.Component {
  state = { descending: true };

  onSortSelect = () => {

    if(this.state.descending) {
      this.setState({ descending: false });
    } else {
      this.setState({ descending: true });
    }

    this.props.onSortSelect(this.state.descending);
  }

  render() {

    const buttonText = this.state.descending ? 'Sort Descending' : 'Sort Ascending';

    return(
      <div class="sort">
        <a onClick={this.onSortSelect}>{buttonText}</a>
      </div>
    );
  }
}

Parent:

class FiltersAndSort extends React.Component {

  onSortSelect = (sort) => {
    console.log(sort);
  }

  render() {
    return(
      <div class="filters-and-sort">
        <Filter />
        <Sort />
      </div>
    );
  }
}

Upvotes: 1

Views: 166

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

You need to pass the function down

<Sort />

should become

<Sort onSortSelect={ this.onSortSelect } />

But you will also have to fix the onSortSelect of the Sort component.

As the this.state.descending you are passing to the method is not the updated one.

onSortSelect = () => {

  this.setState((currentState) => ({
      descending: !currentState.descending
    }), () => {
      this.props.onSortSelect(this.state.descending);
    }
  }
}

Upvotes: 1

Related Questions