React Form Events Demystified: TypeScript Tips and Tricks for Beginners 🚀
Hey there, future coding superstar! Today, we’re exploring the world of React form events with TypeScript. We’ll cover what these events do, their TypeScript types, and some fun examples to show you how they work in practice. Let’s make this as fun and colorful as possible! 🚀
What Are Form Events? 🤔
When you interact with a form on a website — like typing your name, clicking a button, or selecting a checkbox — form events are triggered. These events let your app know what’s happening so it can respond accordingly. In React, we can listen to these events and decide what should happen when they occur.
The Main Form Events and Their TypeScript Types 🛠️
Let’s dive into the key form events in React, their TypeScript types, and see them in action!
1. onChange
: Something Changed! 🔄
- TypeScript Type:
React.ChangeEvent<HTMLInputElement>
When you type into a text input field, an onChange
event is triggered every time you change the value. It’s like telling your app, "Hey, the user just typed something new!"
Example:
import React, { useState } from 'react';
const TextInput: React.FC = () => {
const [text, setText] = useState<string>('');
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setText(event.target.value); // Updates the text state with the input value
};
return (
<div>
<input type="text" value={text} onChange={handleChange} />
<p>You typed: {text}</p>
</div>
);
};
export default TextInput;
2. onSubmit
: Ready to Send! 📤
- TypeScript Type:
React.FormEvent<HTMLFormElement>
This event is triggered when you click the “Submit” button on a form. The onSubmit
event tells your app that the user wants to send all the information they've entered.
Example:
import React, { useState } from 'react';
const SimpleForm: React.FC = () => {
const [inputValue, setInputValue] = useState<string>('');
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevents the form from refreshing the page
alert(`Form submitted with value: ${inputValue}`);
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<button type="submit">Submit</button>
</form>
);
};
export default SimpleForm;
Here, when you submit the form, the onSubmit
event is triggered, preventing the page from refreshing and showing an alert with the input value instead.
3. onFocus
: I'm Paying Attention! đź‘€
- TypeScript Type:
React.FocusEvent<HTMLInputElement>
When you click into a text field or any other form element, an onFocus
event is fired. This event signals that the user is focused on that particular input.
Example:
import React, { useState } from 'react';
const FocusInput: React.FC = () => {
const [message, setMessage] = useState<string>('Click on the input field!');
const handleFocus = () => {
setMessage('You are now focused on the input!');
};
return (
<div>
<input type="text" onFocus={handleFocus} />
<p>{message}</p>
</div>
);
};
export default FocusInput;
In this example, when you click on the input field, the onFocus
event changes the message to let you know the input is focused.
4. onBlur
: Moving On! 🚶‍♂️
- TypeScript Type:
React.FocusEvent<HTMLInputElement>
After you finish typing in a field and click somewhere else, an onBlur
event is triggered. It’s like saying, "Okay, I'm done with this field. Let’s move on!"
Example:
import React, { useState } from 'react';
const BlurInput: React.FC = () => {
const [message, setMessage] = useState<string>('Type something and click away.');
const handleBlur = () => {
setMessage('You have left the input field!');
};
return (
<div>
<input type="text" onBlur={handleBlur} />
<p>{message}</p>
</div>
);
};
export default BlurInput;
Here, when you click away from the input field, the onBlur
event updates the message, letting you know you’ve moved on.
5. onClick
: Click! 👆
- TypeScript Type:
React.MouseEvent<HTMLButtonElement>
When you click a button or any clickable element, the onClick
event is fired. This event handles what happens when the user clicks something.
Example:
import React, { useState } from 'react';
const ClickButton: React.FC = () => {
const [count, setCount] = useState<number>(0);
const handleClick = () => {
setCount(count + 1); // Increment the count when button is clicked
};
return (
<div>
<button onClick={handleClick}>Click me!</button>
<p>You clicked {count} times!</p>
</div>
);
};
export default ClickButton;
In this example, every time you click the button, the onClick
event increments the count and updates the display.
6. onKeyDown
, onKeyUp
, onKeyPress
: Playing with the Keyboard! 🎹
onKeyDown
TypeScript Type:React.KeyboardEvent<HTMLInputElement>
onKeyUp
TypeScript Type:React.KeyboardEvent<HTMLInputElement>
onKeyPress
TypeScript Type:React.KeyboardEvent<HTMLInputElement>
These events handle what happens when the user interacts with the keyboard.
Example:
import React, { useState } from 'react';
const KeyboardEvents: React.FC = () => {
const [key, setKey] = useState<string>('');
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
setKey(`Key Down: ${event.key}`);
};
const handleKeyUp = (event: React.KeyboardEvent<HTMLInputElement>) => {
setKey(`Key Up: ${event.key}`);
};
return (
<div>
<input type="text" onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} />
<p>{key}</p>
</div>
);
};
export default KeyboardEvents;
In this example, when you press and release a key in the input field, the onKeyDown
and onKeyUp
events are triggered, updating the display with the key you pressed.
Thank you for reading. I hope you enjoyed it and learned from it.
Sign up for the mailing list to get notified of the drop of new articles.
For questions and/or suggestions, I am available through the comments section, email gyannickange@gmail.com, or Linkedin @gyannickange
Thank you and we will catch up on the next article!!!