fervor [>]CODING & CURIOSITY
FERVOR LEARNING SYSTEMTUTORIALS
← React

React / 1 MIN READ

onClick Handler

Gotta Handle those clicks

From the original Fervor library. Examples may use older package versions.

  1. Create a new functional component, ClickExample.js:
   import React from 'react';

   const ClickExample = () => {
     const handleClick = () => {
       alert('Button clicked!');
     };

     return (
       <div>
         <button onClick={handleClick}>
           Click me
         </button>
       </div>
     );
   };

   export default ClickExample;
  1. Define the onClick event handler function (handleClick):
   const handleClick = () => {
     alert('Button clicked!');
   };

The handleClick function will be executed when the button is clicked. In this example, it displays an alert with the message “Button clicked!”.

  1. Add the event handler function to an element using the onClick attribute:
   <button onClick={handleClick}>
     Click me
   </button>

The onClick attribute is added to the button element, and the handleClick function is assigned as its value. This tells React to call the handleClick function when the button is clicked.

  1. Import and use the ClickExample component in your main app, for example, in App.js:
   import React from 'react';
   import ClickExample from './ClickExample';

   const App = () => {
     return (
       <div>
         <header>
           {/* Your header content */}
         </header>
         <main>
           <ClickExample />
           {/* Your main app content */}
         </main>
       </div>
     );
   };

   export default App;

Simple and Easy Peeesey.

Keep your curiosity going.Explore more React →
287 TUTORIALS · 22 TOPICSREADY