0

Given a parent component renders the following:

const handleButtonClick = (e) => {
 //code omitted
}
<ChildComponent
 handleButtonClick={handleButtonClick} 
/>

And the child component which adds this handler to a button:

const ChildComponent = (props) => {
  const handleButtonClick = props.handleButtonClick

  return (
    <button onClick={handleButtonClick}>Click me!</button>
  )

}

How would I transform handleButtonClick in the parent in a Rxjs Stream?

I have thought of one way, which is creating a subject:

const clickStream = new Subject()

const handleButtonClick = (e) => {
 clickStream.next(e)
}

I would also be interested in how to do that in a scenario where the parent renders multiple, dynamic children, e.g.:

return(
  <>
   {
     children.map((child, index) => {
        <ChildComponent handleButtonClick={handleButtonClick}/> 
     })
   }
  </>
)
cesartalves
  • 1,507
  • 9
  • 18
  • `fromEvent(button, "onClick").pipe(filter(), mpa(), reduce()).subscribe()` – Mrk Sef Oct 23 '20 at 15:13
  • And how do you suggest I pass the button to `fromEvent` if I don't have a reference to it in the parent component? – cesartalves Oct 23 '20 at 15:26
  • Yeah, using `Subject` for that looks fine. Is there are something that worries you in this approach? (here is similar example https://stackoverflow.com/a/44300853/3772379) – Oles Savluk Oct 23 '20 at 15:33
  • @OlesSavluk I was just wondering if there was another conventional approach, since I am a React beginner. – cesartalves Oct 23 '20 at 16:01
  • First, @cesartalves is right and there's really nothing wrong with using a subject. It comes with (slightly) more overhead as it's multicasted by default. Here's examples of using fromEvent: https://stackoverflow.com/questions/58369735/how-do-i-use-rxjs-fromevent-in-react – Mrk Sef Oct 23 '20 at 16:12
  • @MrkSef I like that idea. My scenario is a bit more complicated because I'm building a grid with multiple, dynamic children. I'm not sure how to dynamically forward those refs, and even if that's possible. However this is the closest to what I had been imagining and I will definitely use it in other scenarios. – cesartalves Oct 23 '20 at 19:12

0 Answers0