Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing multiple methods in props ReactJS

I have a main App component that includes this...

changeAmount(a) {
  console.log('changing: ', a);
}

<Table 
     data={result}
     onClick={() => this.changeAmount()}
/>

The <Table> component then has a <TableRow> component which has two buttons within it. Is there a way to pass multiple onClick methods so I can use one for decrease and one for increase ?

export default class TableRow extends Component {
  render() {
    const {row, onClick} = this.props;
      return (
      <tbody>
        <tr>
            .....
            <span>

              <button 
                 className="btn btn-outline-primary btn-sm minusBtn"
                 onClick={onClick}
              >
                -
              </button>
            .....
          </tr>
      </tbody>
    )
  }
 }

Edit: Tried using one handler with a parameter:

App component:

<Table 
   data={result}
   onClick={(type) => this.changeAmount(type)}
/>

Table component:

{
   data.map(row => (
      <TableRow key={row._id} row={row} onClick={onClick}/>
   ))
}

TableRow component:

<button 
    className="btn btn-outline-primary btn-sm minusBtn"
    onClick={this.props.onClick('decrease')}
>
like image 300
grpcMe Avatar asked Apr 16 '26 01:04

grpcMe


1 Answers

Is there a way to pass multiple onClick methods?

Yes, see in props we can pass any no of data/methods to child component by any key name, it's not necessary to use name onClick when passing method you can use any name like click_one, click_two or click_decrease click_increase.

Like this:

<Table 
    data = {result}
    onClick_increase = {() => this.ABC()}
    onClick_decrease = {() => this.XYZ()}

    abc = {...}
    xyz = {...}
/>

Now you can access these methods from child component by this.props.onClick_increase() and this.props.onClick_decrease().

Another possible way:

You can use same function with both buttons but for that pass a unique identifier from child component along with data to identified whether method is called for decrease or increase.

Like this:

<Table 
     data={result}
     onClick={(type, data) => this.changeAmount(type, data)}
/>

changeAmount(type, data){
    if(type == 'decrease'){
        .....
    }else{
        .....
    }
}

From Child:

this.props.onClick('decrease', data);
like image 63
Mayank Shukla Avatar answered Apr 17 '26 16:04

Mayank Shukla



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!