Thursday, November 28, 2024
Google search engine
HomeLanguagesWhat are synthetic events in ReactJS ?

What are synthetic events in ReactJS ?

In order to work as a cross-browser application, React has created a wrapper same as the native browser in order to avoid creating multiple implementations for multiple methods for multiple browsers, creating common names for all events across browsers. Another benefit is that it increases the performance of the application as React reuses the event object.

It pools the event already done hence improving the performance.

Syntax:

e.preventDefault()
  • e.stopPropagation() prevents the call to the parent component whenever a child component gets called.
e.stopPropagation()

Note: Here ‘e’ is a synthetic event, a cross-browser object. It is made with a wrapper around the actual event of the browser. 

Some of the attributes are:

  • bubbles: Return true or false indicates event is a bubbling event or not.
  • cancelable: Return true or false indicates if the event can be canceled or not.
  • currentTarget: Indicates the element to which the handler is attached
  • defaultPrevented: Return true or false, indicates whether the event has been canceled by preventDefault().
  • eventPhase: Returns number, indicates the phase
  • isTrusted: Return true when the event is generated by the user and false when by the browser/script
  • type: Returns string, it indicates the type of the event

Note: Methods like preventDefault() and stopPropagation() are discussed further.

Creating React Application:

Step 1: Create the react project folder, open the terminal, and write the command npm create-react-app folder name, if you have already installed create-react-app globally. If you haven’t then install create-react-app globally by using the command npm -g create-react-app or can install locally by npm i create-react-app.

npm create-react-app project

Step 2: After creating your project folder(i.e. project), move to it by using the following command.

cd project

Project Structure:

Example 1: In App.js we are creating a simple button that on click shows all the properties of the event in the console. We will see that all the above-mentioned properties there in the console.

Javascript




// App.js
function App() {
    const onClickHandler = (e) => {
        console.log(e);
    }
    return (
        <div className="App">
            <button onClick={onClickHandler}>
                Click
            </button>
        </div>
    );
}
 
export default App;


Output:

Now we will understand about the two void functions: preventDefault(), stopPropagation(),

Note: Currently e.persist() doesn’t do anything as it is no longer pooled.

We will create a form component with an input tag and some buttons, As we know that a submit button by default will refresh the page and the input will be null again but we can prevent the default behavior by using the method preventDefault(), so here we are creating a function name as handlepreventDefault that takes the event as e and stops the default behavior of the submit button.

To understand we have taken two nested spans named as stopPropagation() and inside div that is nested inside the span stopPropagation(), as per the default behavior of the browser, when we click on inside div the method of the parent class also gets trigged in order to prevent that we use stopPropagation(), in the child span so that when clicked on it, it only triggers the method associated with the child span. Here two functions handlestopPropagation and insideDiv have been created which triggers whenever their respective span gets clicked.

Example 2:

Javascript




function App() {
    const handlepreventDefault = e => {
        e.preventDefault();
        console.log("clicked on preventDefault")
    }
    const handlestopPropagation = e => {
        e.stopPropagation();
        console.log("clicked on stopPropagation")
    }
 
    const insideDiv = (e) => {
        e.stopPropagation();
        console.log("clicked on Div")
    }
    return (
        <div className="App">
            <form>
                Type anything: <input />
                <button type="submit"
                    onClick={handlepreventDefault}>
                    preventDefault()
                </button>
                <span onClick={handlestopPropagation}>
                    stopPropagation()
                    <span onClick={insideDiv}> Inside div</span>
                </span>
                <button type="submit">submit</button>
 
            </form>
        </div>
    );
}
 
export default App;


Javascript




// index.js
body {
    margin: 0;
    font - family: -apple - system, BlinkMacSystemFont,
        'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
        'Fira Sans', 'Droid Sans', 'Helvetica Neue',
        sans - serif;
    -webkit - font - smoothing: antialiased;
    -moz - osx - font - smoothing: grayscale;
}
   
code {
    font - family: source - code - pro, Menlo, Monaco,
        Consolas, 'Courier New', monospace;
}
button, span{
    padding: 2px 10px;
    font - size: 20px;
    border: 1px solid black;
    background - color: aliceblue;
    cursor: pointer;
}


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments