Trusted answers to developer questions

React - How to convert to hooks - props

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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
this

CONTRIBUTOR

Stephen Roberts
Attributions:
  1. undefined by undefined
Did you find this helpful?