Auto consume DOM events in a react component
Consume DOM events out of the box for DOM elements
The following code is working of the box: click the button and you will see ‘i was clicked’ on the console
function App() {return (<button onClick={() => console.log('i was clicked')}>ClickMe</button>);}
It is working because by design react give the same flexibility that you have in HTML with regard to handling DOM event
Manual consume DOM event in a react component
However, when you write your component it’s not as simple. Here clicking on the Button will do nothing because the button is unaware of the DOM event
function Button(props) {return <button>{props.children}</button>}function App() {return (<Button onClick={() => console.log('i was clicked')}>ClickMe</Button>);}
You can make it work by manually adding props to the button e.g. clickHandler
function Button(props) {return <button onClick={props.clickHandler}>{props.children}</button>}function App() {return (<Button clickHandler={() => console.log('i was clicked')}>ClickMe</Button>);}
However, if you need to handle more DOM events it requires more code
Auto consume DOM events in a react component
If you want to auto consume any DOM event you need to do the following
function Button({children,...rest}) {return <button {...rest}> {children}</button>}function App() {return (<Button onClick={() => console.log('i was clicked')}>ClickMe</Button>);}
Conclusion
You can consume DOM events in a react component by using props and attaching them to DOM elements like buttons. However, you can eliminate this by using destructuring and spread operators