onClick
An event handler in JavaScript and React that executes a function when a user clicks on an element.
Overview
onClick is one of the most commonly used event handlers in web development. In vanilla JavaScript, it's written as onclick (lowercase), while in React it's onClick (camelCase). It allows you to respond to user clicks and execute code, making your web applications interactive.
Example
javascript// Vanilla JavaScript (HTML attribute) <button onclick="handleClick()">Click me</button> <script> function handleClick() { alert('Button clicked!'); } </script> // Vanilla JavaScript (addEventListener - preferred) const button = document.getElementById('myButton'); button.addEventListener('click', function() { console.log('Button clicked!'); }); // Arrow function button.addEventListener('click', () => { console.log('Clicked!'); }); // React onClick function Button() { const handleClick = () => { console.log('Button clicked!'); }; return ( <button onClick={handleClick}> Click me </button> ); } // React with parameters function Counter() { const [count, setCount] = useState(0); const increment = () => { setCount(count + 1); }; return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); } // Preventing default behavior function Link() { const handleClick = (e) => { e.preventDefault(); console.log('Link clicked but default prevented'); }; return ( <a href="/" onClick={handleClick}> Click me </a> ); } // Event object button.addEventListener('click', (event) => { console.log('Element:', event.target); console.log('X coordinate:', event.clientX); console.log('Y coordinate:', event.clientY); });
Key Points
- Executes function on user click
- In React: onClick (camelCase)
- In HTML: onclick (lowercase)
- addEventListener preferred in vanilla JS
- Can access event object for details
Learn More
- Event - Event handling
- addEventListener - Event listeners
- Component - React components
- MDN: onclick