Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make React listen to event in Child component first instead of Parent component?

Consider this example

<div onClick={() => redirectTo('/foo')}>
  <input type="text"/>
  <input type="button" onClick={() => redirectTo('/bar')} />
</div>;

when i test this example in this case by click to second input , React always redirect to /foo, is that normal behavior and how can i make React redirect to /bar? Thanks a lot!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The click event is propagating from the input to the div and both redirects occur. You are seeing the result of the last redirect.

You can stop the propagation of the input’s click event.

<div onClick={() => redirectTo('/foo')}>
  <input type="text"/>
  <input
    type="button"
    onClick={(e) => {
      e.stopPropagation();
      redirectTo('/bar');
    }}
  />
</div>;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading