Events in React

 In react, handling event is very similar to handling events on DOM elements. Rather than defining the name of events in lowercase we use camelCase.

       Example: HTML: onclick, React: onClick

There are some most used react events described as follows:

1. onClick:

        Whenever a user clicks on a button or any element, onClick event triggers.

        Example:

                Using arrow function:

                <button onClick ={()=>{

                       alert("Button Clicked");

                }}>

                      Alert

                </button>


                Using JS function:

                function showAlert(){

                      alert("Button Clicked");

               }

               <button onClick={showAlert}>

                   Alert

               </button>


2. onChange:

             Whenever the value of an HTML element changes, this event is triggered.

             const TypeEffect = () => {

                     const [content, setContent] = useState("");

                     return(

                            <>

                                  <h4>Start Typing:</h4>
                                  <p>{content}</p>
                                  <input type="text" placeholder = "type here" onChange={(e)=>setContent(e.target.value)}>
                            </>

                     );

             }

             export default TypeEffect;


           Call this component as <TypeEffect /> and check for the result.


3. onSubmit:

         This event is used mostly with form Elements. It will trigger when form is submitted.

         Example:

               <button type="submit" onSubmit={handleSubmit}>

                   Submit

               </button>

           Here handleSubmit() is some function.


There are many more react events defined, which we'll discuss throughout the course.

Continue Learning: Lifecycle Methods in React

Comments

Popular Posts