Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to refer to immediately destructured props in class component, do I have to use `this.props` every time?

In a stateless functional component, we can use destructured props as the function arguments:

const Blah = ({ hello, world }) {
  return <div>{hello} {world}</div>
}

This gives very clean code and not only is it obvious what props are being passed, we don't have to use this.props everywhere.

Having to use this.props all the time in a class component can take up a lot of room all over the component and is not nearly as nice to use:

class Blah extends Component {
  render() {
    return (
      <div>{this.props.hello} {this.props.world}</div>
    )
  }
}

My questions is, what similar approach can we take for class components so that we don't have to use this.props everywhere?

One solution I can think of would be to destructure the props in the render method, but of course you would have to do that for every method in your class should you want to use the destructured name.

like image 543
alanbuchanan Avatar asked Dec 03 '25 04:12

alanbuchanan


1 Answers

Nope I'm afraid there's no way to. The functional component is essentially a render() function of a class component, the "cleaniness" is kinda the same actually (:

like image 63
Yangshun Tay Avatar answered Dec 05 '25 19:12

Yangshun Tay