Key Summary
This article from InApps Technology, authored by Phu Nguyen, provides a concise tutorial on handling the onClick event in React, a popular JavaScript library for building user interfaces. It explains how to implement click event handlers, common pitfalls, and state management using onClick, with practical code examples. Key points include:
- React Event Handling:
- React events use camelCase syntax (e.g., onClick instead of onclick) and are assigned functions within curly braces (e.g., onClick={function}).
- The onClick handler triggers a function when a DOM element (e.g., a button) is clicked.
- Basic Example:
- Setup: Create a React project with npm create-react-app reactOnClick, navigate to the directory (cd reactOnClick), and start it (npm start).
- Code Example (in src/App.js):
javascript
CollapseWrapRun
Copy
import React from ‘react’;
function App() {
const testClick = () => {
alert(‘Hey, you just clicked me’);
};
return (
<div className=“App”>
<button onClick={testClick}>Click me!</button>
</div>
);
}
- export default App;
- Result: Clicking the button triggers an alert: “Hey, you just clicked me.”
- Common Mistake:
- Incorrect Usage: Using onClick={testClick()} calls the function on every render, not on click.
- Correct Usage: Use onClick={testClick} or an inline function like onClick={() => alert(‘Message’)}.
- Passing Arguments to Functions:
- Use an inline function to pass parameters:
javascript
CollapseWrapRun
Copy
- Use an inline function to pass parameters:
const testClick = (name) => {
alert(‘Hello ‘ + name);
};
- return <button onClick={() => testClick(‘John’)}>Click me!</button>;
- Result: Displays an alert: “Hello John” on click.
- State Management with onClick:
- Use the useState hook to manage state changes triggered by clicks:
javascript
CollapseWrapRun
Copy
- Use the useState hook to manage state changes triggered by clicks:
import React, { useState } from ‘react’;
function App() {
const [count, setCount] = useState(0);
return (
<div className=“App”>
<h1>Button is clicked {count} times</h1>
<button onClick={() => setCount(prevState => prevState + 1)}>
Click me!
</button>
</div>
);
}
- export default App;
- Result: Displays a counter that increments with each button click.
- Key Takeaway:
- The onClick event listens for click events on DOM elements, enabling dynamic interactions in React applications.
- Proper function assignment and state management are critical for effective event handling.
- InApps Insight:
- InApps Technology leverages React for interactive UI development, integrating Microsoft’s Power Platform and Azure, using Power Fx for low-code event-driven solutions and Azure Durable Functions for scalable workflows.
- Combines Node.js, Vue.js, GraphQL APIs (e.g., Apollo), and Azure to deliver responsive, user-centric applications, targeting startups and enterprises with Millennial-driven expectations.
Events can be handled in React quite similar to the way we do in HTML, these events be like click, change, mouseover, etc. But ‘React events’ are written in camelCase syntax.
For example: “onClick”instead of “onclick” and the function which this event point to would be written in curly braces, for example: onClick={function}.
In this blog, we will talk only about ‘onClick‘ event handling. The onClick handler allows you to call a function and perform an action when an element is clicked.
Let’s learn about this with an example–
Create a new project by the following command:
npm create-react-app reactOnClick
where, reactOnClick is the project name.
Now, go to the project directory and start it-
cdreactOnClick
npm start
You should have your project started in the localhost.
Now, in src/App.js, add the following code:
import React from 'react';
function App() {
const testClick = () => {
alert('Hey, you just clicked me');
};
return (
<div className="App">
<button onClick={testClick}>
Click me!
</button>
</div>
);
}
export default App;
In this, we have a button which when clicked calls the function “testClick” ,which alerts the user that he clicked the button.
You will see something like the following after clicking the button–
Some common mistake people do is that they pass the function to the handler with parentheses like:
<button onClick={testClick()}>
what it would do is, call the “testClick” function on every render without even clicking it.
It is not necessary to call a function with a name, we can also call inline functions just like:
<button onClick={() => alert('Hey, you just clicked me')}>
So now you must be thinking, if we cannot pass the function name with parentheses then how can we pass arguments to a function.
It can be easily done with an inline function calling that function.
To be more clear, see the following code:
function App() {
const testClick = (name) => {
alert('Hello ' + name);
};
return (
<div className="App">
<button onClick={() => testClick('John')}>
Click me!
</button>
</div>
);
}
You will see the following in your browser:
Similarly, the states can be managed by ‘onClick’ events-
import React, {useState} from 'react';
function App() {
const [count, setCount] = useState(0);
return (
<div className="App">
<h1>Button is clicked {count} times</h1>
<button onClick={() => setCount(prevState =>
prevState + 1)}>
Click me!
</button>
</div>
};
}
export default App;
And in the browser, we have-
So, Event handlers determine what action should be taken when an event occurs. The “onClick” event is used to listen for click events “onDOM” elements.
Hope you all have a clear picture about ‘onClick’ event handling. Will be sharing more such concepts in my future posts.
Source: InApps.net
Let’s create the next big thing together!
Coming together is a beginning. Keeping together is progress. Working together is success.