Dion Dirza Dion Dirza - 3 months ago 21
React JSX Question

React passing parameter with arrow function in child component

I have these parent and child component, I want to pass click function to select an item in child component. Yet it seems the function in child component become automatically called instead of waiting until the user click the element. To make it clearer here is my parent and child components

export class ParentView extends Component {
state = {
selectedItem: {}
}

handleClick = (item) => {
alert('you click me');
this.setState({selectedItem: item});
}

render() {
let item = { name: 'Item-1' };
return (
<div>
<ChildItem item={item} handleClick={this.handleClick} />
</div>
);
}
}

export class ChildItem extends Component {
render() {
const {item, handleClick} = this.props;
return (
<div>
<a onClick={handleClick(item)} />
</div>
);
}
}


Those are my components using arrow function to pass
handleClick
to child component, yet alert always being called at first render without being triggered by user. Any suggestion?

Answer

You should pass a function itself to onClick.

If you would like to invoke it with param, you have options:

  • bind it with item
  • pass new arrow function like () => handleClick(item)

An example below:

export class ChildItem extends Component {
  render() {
    const {item, handleClick} = this.props;
    return <div>
      <a onClick={handleClick.bind(this, item} />
    </div>
  }
}

In your code you're invoking function in onClick declaration.

<a onClick={handleClick(item)} />