As the title indicates, i'm looking for a way for the form onChange event to be triggered without user direct interference. This has more to do with Javascript itself but i'm using React to exemplify what i'm looking for:
I have a custom component DropDown:
function DropDown() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
const selectRef = useRef()
useEffect(() => {
selectRef.current.value = selectedPerson.id
}, [selectedPerson])
return (
<>
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
{({ open, disabled, value }) => {
console.log()
return (
<div>
<Listbox.Button as="div">
<span>{selectedPerson.name}</span>
</Listbox.Button>
<Listbox.Options static style={{ display: open ? 'block' : 'none' }}>
{people.map(person => (
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</div>
)
}}
</Listbox>
<div>
<select ref={selectRef} name="test" id="">
{people.map(person => (
<option key={person.id} value={person.id}>
{person.name}
</option>
))}
</select>
</div>
</>
)
}
the "pure" is going to be hidden, it's just there so i can try and trigger my onChange event of the form that surrounds the component
import DropDown from './DropDown'
import './App.css'
function App() {
const onChange = ev => {
console.log(ev)
}
return (
<div className="App">
<form onChange={onChange}>
<DropDown />
</form>
</div>
)
}
export default App
As you can see, in my useEffect, i successfully change the selected value of my component but i want it to trigger the onChange event on the form, same way as it happens when i change the option directly in the Select.
To be clear, I'm trying to avoid prop drilling the onChange function down to the DropDown component.
Is there a way for this to happen?