NealVDV
NealVDV

Reputation: 2532

Correct way to pass an argument to parent component callback in react

After writing a quite large application for the first time with react I've come accross an issue where my re-renders are basically freezing the UI which is so bad for the UX.

I did not know that passing an anonymous function as a prop caused the entire receiving component every time. So now I'm trying to fix my functions but find it quite hard to get right.

So currently I have a component called NavBar which has subcomponents called NavBarLink. Each NavBarLink calls the same showPopup(arg) function. The argument for showPopup(arg) however is based on which NavBarLink is clicked.

Example

render() {
    return (
        <NavBarLink onClick={() => showPopup("UNIQUE_POPUP_ID")}>Link 1</NavBarLink>
        <NavBarLink onClick={() => showPopup("ANOTHER_POPUP_ID")}>Link 2</NavBarLink>
    );
}

Question

How can I have the same developer experience but don't suffer from the re-rendering issues?

Related articles

Upvotes: 0

Views: 1815

Answers (1)

Alex Bass
Alex Bass

Reputation: 2422

To stop the function being created on each render, you can define them as class methods, and pass the IDs as props to each NavBarLink

class MyComponent {
  handleClick = (id) => {
    return showPopup(id)
  }

  render () {
    return (
      <div>
        <NavBarLink onClick={this.handleClick} id='UNIQUE_POPUP_ID'>Link 1</NavBarLink>
        <NavBarLink onClick={this.handleClick} id='ANOTHER_POPUP_ID'>Link 2</NavBarLink>
      </div>
    )
  }
}

then in your NavBarLink class, you add another method to call the handler with the ID passed in the props.

class NavBarLink {
  handleClick = () => {
    this.props.onClick(this.props.id)
  }

  render () {
    return (
      <a onClick={this.handleClick}>...</a>
    )
  }
}

I hope I interpreted your question correctly!

Upvotes: 3

Related Questions