Trigger change event for displayed React input (type = range)

"react": "^ 15.4.2"

I'm having trouble firing a change event from jquery for an input presented with React. I need to do this to complete testing.

here's a sandbox as a complete showcase: https://codesandbox.io/s/pp1k1kq3om with jquery already loaded.

If you run: $ ('# responseSlider'). val (50) .change () in the console, you will notice that the change handler is not called.

The sandbox above also has a clean html slider for comparison that works as expected (change function is called).

also tried to send a new event like this:

var event = new Event('change')
var target = $('#reactSlider')[0];
target.dispatchEvent(event);

      

The above doesn't work (and works on a pure html slider).

import React from "react";
import { render } from "react-dom";

const changeHandler = event => {
  alert(`react slider changed:${event.target.value}`);
};

const App = () => (
  <div>
    <label htmlFor="reactSlider">react-slider</label>
    <input
      id="reactSlider"
      type="range"
      onChange={changeHandler}
      min={10}
      max={100}
      step={10}
      value={20}
    />
    <p>run in the console: $('#reactSlider').val(50).change()</p>
    <br />
    <br />
    <p>Notice that for the React slider, the change event is not triggered.</p>
  </div>
);

render(<App />, document.getElementById("root"));

      

0


source to share


1 answer


Ok, so I found a workaround. it looks like the onInput event could be called just fine. In case of input type = 'range', the "enter" event is triggered in the same situation as the "change", so I was able to toggle it.

The workaround would be to use onInput instead of onChange and call it like this:



function triggerChange(selector,evt) {
    let ev = new Event(evt, { bubbles: true });
        let el = $(selector)[0]

        el.dispatchEvent(ev);
  };
triggerChange('#reactSlider','input');

      

0


source







All Articles