I\'m new to React.js. I\'m trying to trigger keypress event for text div.
Here is text box code for which I want to execute keypress trigger.
If you create a reference to the div, then you can trigger an event on it. With hooks, you can use useRef. Without hooks, you can use createRef.
With hooks:
function MyComponent() {
const ref = useRef();
// This is simply an example that demonstrates
// how you can dispatch an event on the element.
useEffect(() => {
ref.dispatchEvent(new KeyboardEvent('keypress', {
key: 'Enter',
}));
}, []);
return (
);
}
Without hooks:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.ref = React.createRef();
}
// This is simply an example that demonstrates
// how you can dispatch an event on the element.
triggerKeyPress() {
this.ref.dispatchEvent(new KeyboardEvent('keypress', {
key: 'Enter',
}));
}
render() {
return (
);
}
}
el.dispatchEvent(new KeyboardEvent('keypress',{'key':'a'}));