Professional Documents
Culture Documents
FEWD Unit3
FEWD Unit3
In React, events are the "actions" that can be handled by React components.
These events could be user actions like mouse clicks, key presses, form
submissions, etc., or system-based, such as the completion of an API request.
1. React's Synthetic Events
React wraps DOM events with its own event system, known as "Synthetic
Events". This system provides a consistent API across different browsers
(because different browsers might implement events differently). So, when you
work with events in React, you're working with these Synthetic Events, not the
native browser events directly.
2. Event Handlers
Event handlers are the methods that you define in your React components to
respond to events. These handlers receive an instance of `SyntheticEvent`,
which wraps around the browser's native event.
Example:
function ClickableComponent() {
function handleClick(event) {
alert('Button was clicked!');
console.log(event); // This logs the SyntheticEvent object
}
return <button onClick={handleClick}>Click me</button>;
}
export default ClickableComponent;
3. Passing Arguments to Event Handlers
If you want to pass an argument to an event handler, you can use an arrow
function.
Example:
function ListComponent() {
function handleItemClick(id, event) {
alert(`Item with ID ${id} was clicked!`);
}
return (
<div>
<button onClick={(e) => handleItemClick(1, e)}>Item 1</button>
<button onClick={(e) => handleItemClick(2, e)}>Item 2</button>
</div>
);
}
4. Event Types
React supports many types of events, including:
- Clipboard Events: `onCopy`, `onCut`, `onPaste`
- Form Events: `onChange`, `onSubmit`, `onInput`, etc.
- Keyboard Events: `onKeyDown`, `onKeyPress`, `onKeyUp`
- Mouse Events: `onClick`, `onDoubleClick`, `onMouseMove`, etc.
- And many more...
These events are named using camelCase, and you pass the corresponding
handler as a prop.
Example:
function KeyboardComponent() {
function handleKeyPress(event) {
if (event.key === 'Enter') {
alert('You pressed the Enter key!');
}
}
return <input onKeyPress={handleKeyPress} />;
}
Example:
function FormComponent() {
function handleSubmit(event) {
event.preventDefault();
alert('Form was submitted without a page refresh!');
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
); }
In summary, event handling in React is about listening for user actions or
system events, and responding appropriately using methods defined in your
components. With the Synthetic Event system, React provides a consistent way
to handle events across different browsers.
a) Constructor binding:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(this);
}
render() {
return <button onClick={this.handleClick}>Click me</button>;
}
}
b) Class field with arrow function (most common):
render() {
return (
<div>
{this.state.isLoggedIn && <WelcomeMessage />}
<button onClick={this.handleToggle}>
{this.state.isLoggedIn ? 'Logout' : 'Login'}
</button>
</div>
);
}
c) Using if/else:
render() {
if (this.state.isLoggedIn) {
return <LogoutButton onClick={this.handleLogout} />;
} else {
return <LoginButton onClick={this.handleLogin} />;
}
}
- In React, forms maintain their state locally. You can control this by making the
React state the single source of truth for form elements.
- React forms are typically "controlled", meaning the form data values are
handled by the React component using them.
Example
class SimpleForm extends React.Component {
state = {
name: ""
};
render() {
return (
<input value={this.state.name} onChange={this.handleChange} />
);
}
}
Theoretical Notes:
- Dynamic components help in reusability and scalability. Instead of hardcoding
every input, you create a general-purpose input component that can cater to
different types.
- Dynamic components can also handle validation, formatting, and additional
logic, making your forms smarter and more interactive.
- Props play a pivotal role here. Props like `inputType`, `value`, and `onChange`
allow the parent component to control the child (input component) and its
behavior.
Example
function DynamicInput({ inputType, value, onChange }) {
return (
<input type={inputType} value={value} onChange={onChange} />
);
}
// Usage
<DynamicInput inputType="text" value={this.state.name}
onChange={this.handleChange} />
3. Setting up a JS Config for Form
Theoretical Notes:
- A JS config is a structured way to define the metadata of form elements. It can
include attributes like ID, label, type, validation rules, and more.
- This approach abstracts the static and repetitive aspects of form creation. It
helps in the dynamic generation of forms, making it easier to add, remove, or
modify fields without touching the JSX.
Example
const formConfig = [
{
id: "name",
label: "Name",
type: "text"
},
{
id: "email",
label: "Email",
type: "email"
}
];
Theoretical Notes:
- With the config set, the form fields can be dynamically generated using
JavaScript's map function or other iterators.
- This approach ensures that the form's UI and behavior remain consistent and
centralized.
- Any changes made to the JS config would reflect in the form, thereby ensuring
you only have to make changes in one place.
Example
class DynamicForm extends React.Component {
state = {
name: "",
email: ""
};
render() {
return (
<form>
{formConfig.map(field => (
<div key={field.id}>
<label>{field.label}:</label>
<DynamicInput
inputType={field.type}
value={this.state[field.id]}
onChange={this.handleChange.bind(this, field.id)}
/>
</div>
))}
</form>
);
}
}
Theoretical Notes:
- As users type or interact with form elements, React can capture these
interactions in real-time.
- Using controlled components, the value of the form elements is controlled by
the React state. Hence, every change to the input updates the state, and the
component re-renders displaying the new value.
- The `onChange` event listener is crucial in this scenario as it captures every
keystroke or change and updates the React state accordingly.
Example
handleChange = (id, event) => {
this.setState({ [id]: event.target.value });
}
Theoretical Notes:
- Submitting a form typically involves collecting the data from various fields and
sending it to a server or handling it as per the application's requirements.
- React's synthetic event system captures the `onSubmit` event on forms. The
default behavior (page reload) should be prevented using
`event.preventDefault()`.
- Once the data is captured and possibly validated, it can be sent to a server
using methods like fetch, axios, or any other method suitable for the project's
architecture.
- Feedback, in terms of success or error messages, enhances user experience
and should be integrated as a part of form submission handling.
Example
class DynamicForm extends React.Component {
// ... code ...
render() {
return (
<form onSubmit={this.handleSubmit}>
{/* ... other code ... */}
<button type="submit">Submit</button>
</form>
);
}
}