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

Time:11-15

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!

CodePudding user response:

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>;
  • Related