Home > OS >  Can I simulate a change event using an input ref in React?
Can I simulate a change event using an input ref in React?

Time:11-17

So, I have a component that looks like this:

  <Parent>
    <Sibling1 onChange={() => onChangeThatChangesParent}/> (Searchbar component that renders an input)
    <Sibling2 onClick={() => clearSearchbar}/> (button)
  </Parent>

Sibling1

const Sibling1 = ({onChangeThatChangesParent}) => {

  const handleChangeInternal = () => {
    onChangeThatChangesParent()
    otherFunctions()
  }
      return (
        <input onChange={handleChangeInternal}/>
      )
    }

Where Sibling1 is a component that renders an input and Sibling2 is a button. I need to trigger a onChange event on the input when I click the button. The way I thought of doing that is to pass a reference from the Parent to Sibling1 and to manually trigger a change event when the button is pressed.

Is this possible? How could I trigger a change event in this situation?

Note that I cannot just set the input value using the Ref because upon triggering the change event in Sibling1 a few other functions are executed.

Thanks in advance!

CodePudding user response:

I believe this question awnsers what you want to do:
What is the best way to trigger onchange event in react js

You should check out the accepted awnser by @Grin

  • Related