Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
hooks
communitycreator
this

React - How to convert to hooks - props

Stephen Roberts

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

I discussed in my shot how we may convert a pre-hooks class component in an existing application into a hooks-based functional component with a focus on State. This post will consider how you can still access props passed down from a parent component in a legacy application in your newly modified hooks-based component.

This is a lot simpler than State (which was pretty simple itself), but it doesn’t take advantage of the useContext hook – that treat is for another shot!

Pre-Hooks Code

We have a class component with the constructor method at the top of the page…

export class SearchResults extends Component {
  constructor(props) {
    super.props;

    this.state = {
      inputFilter: ''
    };
  }
}

…and then we call this.props to access the data being passed down by the parent component:

renderDataRow() {
  const entries = [];

  this.props.data.filter(item => !this.state.inputFilter || ...
  ...

Hooks

We declare our functional component…

export cost SearchResults = (props) => {

…and we pass in props as a parameter to the child component…

const renderDataRow() {
  const entries = [];

  props.data.filter(item => !inputFilter || ...
  ...

…then call props directly – no need for this!

Conclusion

That was it – just a simple note of how your newly made hooks component can access props when you’re updating a legacy application -> pass it in as a parameter.

RELATED TAGS

react
hooks
communitycreator
this

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring