42

I've applied eslint airbnb standard to my code, so now this code:

handleSubmit = (event) => {
  event.preventDefault();
  this.props.onSearch(this.query.value);
  event.target.blur();
}

causes this error:

[eslint] Must use destructuring props assignment (react/destructuring-assignment)

onSearch basically a trigger that passes up a value to parent component.

How do I refactor this code to meet the eslint requirements?

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Dominik Domanski
  • 1,023
  • 2
  • 10
  • 18

1 Answers1

46
handleSubmit = (event) => {
    event.preventDefault();

    const {onSearch} = this.props
    const {value} = this.query
    onSearch(value)

    event.target.blur();
}
lomse
  • 4,045
  • 6
  • 47
  • 68
  • Thanks! I still can't compute how do I invoke this onSearch function from child component – Dominik Domanski Nov 17 '18 at 16:15
  • 1
    You can pass `onSearch` function as a prop to the child component – Eugene Dzhevadov Nov 17 '18 at 16:29
  • 39
    In my opinion, this answer perfectly illustrates why this is not a good lint rule to have enabled. Destructuring should be used where it improves readability but using it everywhere for consistency is counter productive. Here it requires you to turn 3 lines into 5 with 2 throwaway `const` assignments i.e. less readable and less performant – Jon Wyatt Jun 25 '19 at 08:24
  • 2
    Destructuring is great when you have more than one value, const { className, title, text } = this.props; Much better than this.props.title and so on. – Sergey Grabak Aug 07 '19 at 03:46
  • @JonWyatt it's safer, especially in this case where `this.props.onSearch` could mess with `this.props` if using `this` in its implementation if `onSearch`'s context was incorrectly bound, leading to sneaky problems that are hard to debug. When destructuring, incorrect context binding will fail fast, and minification will remove any unnecessary variables in the end, so performance is a non-issue. Using strict rules like this one will avoid problems that a team might not even be aware of. – Emile Bergeron Oct 15 '19 at 21:35