0

I try to find solution how to handle events in React parent<->children components without external libraries.

Example, let's imagine we build Select (dropdown) component. Inside one parent component there are children components like leftIcon, Content, Tags, Search, OpenClose, List etc.

To pass only value I use Context and Reducer effects but I don't know how to pass events and handle it in parent component. Let's imagine there is a need to handle click event on all children.

First idea is to pass callback through props but from my perspective is not good. Second idea is to pass some how through Reducer's state callback and I didn't find any examples how it can be.

I appreciate any idea or solutions how to manage it. Thank you.

I also tried to create own EventEmitter to subscribe/unsubscribe but it was overmuch code.

UPD. Pass callback through components by props is normal practice. Let's imagine that there is something like nested components parent->child1->child2->child3->child4. There is a need to pass callback from parent to child4. Of course, It can be through props. But maybe there is more interested and simple solution.

  • 2
    `First idea is to pass callback through props but from my perspective is not good` why? That's how parents find out about events that happen on children by default in React. That's how 'onClick' works on a button element. What's wrong with using props like this? – TKoL Aug 29 '23 at 11:42
  • Does this answer your question? [How to pass props to {this.props.children}](https://stackoverflow.com/questions/32370994/how-to-pass-props-to-this-props-children) – André Aug 29 '23 at 11:53
  • I have added example below. Please read it. Don't want to duplicate it :) – Dmytro Hotovskyi Aug 29 '23 at 12:16

1 Answers1

0

From the way you're phrasing everything you might be coming from Angular? I had the same issue, but in React there are different patterns compared to Angular. That's exacly how you do it, through props (see example). You can also see an example in their official documentation here.

export default function Parent() {
  const handleClickEvent = (e) => console.log('here we handle click event from child', e);
  
  return <Child handleClickEvent={handleClickEvent} />
}


export default function Child({handleClickEvent}) {
  return (
    <button onClick=(handleClickEvent)>
      Click me to trigger parent handler!
    </button>
   )
}
ivy
  • 1
  • 1
  • Pass callback through components by props is normal practice. Let's imagine that there is something like nested components "parent->child1->child2->child3->child4". There is a need to pass callback from parent to child4. Of course, It can be through props. But maybe there is more interested and simple solution. – Dmytro Hotovskyi Aug 29 '23 at 12:14