react2angular icon indicating copy to clipboard operation
react2angular copied to clipboard

Is there a way to pass a function with params to a react component

Open phliem opened this issue 6 years ago • 4 comments

If I have a parent angular component and I want to pass a function without any parameters to a react child component, this will work Screenshot 2019-03-26 at 10 28 32

The problem is that I need to pass some parameter in the chooseSolution function. This will not work as the chooseSolution function is immediately invoked and I will have an infinite loop error Screenshot 2019-03-26 at 11 09 11

And here is the error Screenshot 2019-03-26 at 11 18 35

What I don't really understand is the reason why the function chooseSolution is invoked as soon as I pass a parameter from an angular parent component to a react child component.

I have recreate the problem here (Angular Parent and React Child) https://stackblitz.com/edit/react2angular-fkbnpd?file=angular-component.js

If I recreated the same example in an Angular Parent and Angular Child context, it will work without immediately invoking my function chooseSolution. Here is an working example (Angular Parent and Angular Child) https://stackblitz.com/edit/react2angular-my4bmr?file=angular-component.js

Note that I cannot create two functions like the following, because the number of buttons is a dynamic value. For example i will have 10 different buttons, so can't really create 10 different functions dynamically Screenshot 2019-03-26 at 11 25 04

phliem avatar Mar 26 '19 12:03 phliem

hello, i just found my way here through a google search and have never used this library, so this might not work, but have you tried passing in in an arrow function?

() => $ctrl.chooseSolution('SOLUTION_A’)

nnals avatar Apr 03 '19 18:04 nnals

hello, i just found my way here through a google search and have never used this library, so this might not work, but have you tried passing in in an arrow function?

() => $ctrl.chooseSolution('SOLUTION_A’)

Hi nnals, thanks for your help! I already tried the arrow function without success previously. It endup in a syntax error

phliem avatar Apr 04 '19 07:04 phliem

The reason the function chooseSolution is invoked is because the angular component created with react2angular binds via one-way bindings (<) rather than callback bindings (&).

A possible solution is to define chooseSolution to be (solution) => () => { /*do whatever you actually want to do*/ };.

(Apologies for any poor formatting - on my phone).

tristanHessell avatar Apr 04 '19 10:04 tristanHessell

@phliem try this solution: https://github.com/coatue-oss/react2angular/issues/43#issuecomment-446645871

In controller should create arrow function:

tip: solutionName is invented variable name

chooseSolution = solutionName => { /* something */ }

And to correct parse this code you should install babel plugin @babel/plugin-proposal-class-properties

kanapka94 avatar Jan 30 '20 16:01 kanapka94