React event handling
Created By: chatGPT
React offers a simple way to handle events, allowing you to interact with user inputs and respond accordingly. Event handlers are written in camelCase, and you can pass a function as a prop to the event handler. Let's look at a basic example of handling a button click event.
import React from 'react';
function MyButton() {
const handleClick = () => {
alert('Button was clicked!');
};
return <button onClick={handleClick}>Click Me!</button>;
}
export default MyButton;
In the above code, we define a handleClick function that triggers an alert when the button is clicked. The
onClick
prop is set to this function. In React, you can also pass parameters to event handlers.import React from 'react';
function GreetingButton({ name }) {
const handleClick = (name) => {
alert(`Hello, ${name}!`);
};
return <button onClick={() => handleClick(name)}>Greet</button>;
}
export default GreetingButton;
Here, the
GreetingButton
component takes a name
prop and uses it within the handleClick
function. We're using an arrow function in the onClick
handler to pass the name
argument. This is how you can effectively customize your event handling.import React from 'react';
function App() {
return (
<div>
<GreetingButton name='Alice' />
<GreetingButton name='Bob' />
</div>
);
}
export default App;
In
App
, we render two GreetingButton
components with different names. This shows how you can reuse event handlers effectively in a component-oriented design.import React, { useState } from 'react';
function ToggleButton() {
const [isToggled, setIsToggled] = useState(false);
const handleToggle = () => {
setIsToggled(prev => !prev);
};
return <button onClick={handleToggle}>{isToggled ? 'ON' : 'OFF'}</button>;
}
export default ToggleButton;
Next, we can manage the state of the button by toggling its text between 'ON' and 'OFF'. The state is managed using the
useState
hook. Whenever the button is clicked, handleToggle
updates the state seamlessly.import React from 'react';
function App() {
return <ToggleButton />;
}
export default App;
Rendering
ToggleButton
in the App
component demonstrates how you can create a button with interactive state management. This approach will help in building more dynamic user interfaces.import React from 'react';
function App() {
const handleFormSubmit = (event) => {
event.preventDefault(); // Prevents page reload
console.log('Form submitted!');
};
return (
<form onSubmit={handleFormSubmit}>
<input type='text' placeholder='Type something' />
<button type='submit'>Submit</button>
</form>
);
}
export default App;
Handling form submissions is as straightforward as any other event. Here, the
handleFormSubmit
prevents the default form submission behavior using event.preventDefault()
. This is crucial for preventing the page from reloading and allows for custom handling of the form data.import React from 'react';
function App() {
return <FormComponent />;
}
export default App;