onClick fires whenever the element it's attached to, or one of its descendants since it bubbles, is clicked, calling the provided handler function with a SyntheticMouseEvent object containing details like which mouse button was pressed, the click's coordinates, and standard methods like preventDefault() and stopPropagation(). It works on virtually any element, not just buttons and links, letting you make arbitrary elements, like a div or a table row, clickable, though for accessibility, genuinely interactive elements should generally be actual buttons or links rather than a div with an onClick handler and no other semantic or keyboard support.
1Understanding onClick
onClick fires whenever the element it's attached to, or one of its descendants since it bubbles, is clicked, calling the provided handler function with a SyntheticMouseEvent object containing details like which mouse button was pressed, the click's coordinates, and standard methods like preventDefault() and stopPropagation(). It works on virtually any element, not just buttons and links, letting you make arbitrary elements, like a div or a table row, clickable, though for accessibility, genuinely interactive elements should generally be actual buttons or links rather than a div with an onClick handler and no other semantic or keyboard support.
Avoid making a plain div the sole clickable target for an important action — use an actual button, or add proper keyboard and ARIA support, so the element remains accessible to keyboard and screen-reader users, not just mouse users.
function LikeButton() {
const handleClick = () => console.log('Liked!');
return <button onClick={handleClick}>Like</button>;
}2Practical Example
Here is a real-world application of onClick showing how it is used in production React code.
function Card({ onSelect, id }) {
return (
<div onClick={() => onSelect(id)}>
<button onClick={(e) => { e.stopPropagation(); console.log('Delete clicked'); }}>Delete</button>
</div>
);
}3Best Practices
Follow these guidelines when working with onClick:
1. Prefer semantic elements like <button> for clickable actions over a <div> with onClick, for built-in keyboard accessibility and screen-reader support
2. Use event.stopPropagation() inside a nested element's onClick handler if you need to prevent the click from also triggering a parent element's own onClick due to bubbling
3. Pass a function reference, or an inline arrow function when arguments are needed, never a direct function call, to onClick
Tip: Avoid making a plain div the sole clickable target for an important action — use an actual button, or add proper keyboard and ARIA support, so the element remains accessible to keyboard and screen-reader users, not just mouse users.
function LikeButton() {
const handleClick = () => console.log('Liked!');
return <button onClick={handleClick}>Like</button>;
}