React blur event typescript

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Typescript] Type of onBlur and onFocus events #17369

[Typescript] Type of onBlur and onFocus events #17369

Comments

  • The issue is present in the latest release.
  • I have searched the issues of this repository and believe that this is not a duplicate.
Читайте также:  Css свойства к двум

Current Behavior 😯

The latest update seemed to change the type of onBlur and onFocus events (at least for TextField)

export interface FormControlTypeMap, D extends React.ElementType = 'div'> < props: P & < disabled?: boolean; error?: boolean; fullWidth?: boolean; hiddenLabel?: boolean; margin?: PropTypes.Margin; onBlur?: React.EventHandler; onFocus?: React.EventHandler; required?: boolean; variant?: 'standard' | 'outlined' | 'filled'; >; defaultComponent: D; classKey: FormControlClassKey; > 

Shouldn’t they be React.FocusEvent as they used to be?

Your Environment 🌎

The text was updated successfully, but these errors were encountered:

function Whatever()  const handler = React.useCallback((ev?: React.FocusEventHTMLInputElement>) => >, []) return ( TextField onFocus=handler> /> ); >

In 4.4.0 it was defined as ReactFocusEvent , now it gives an error on compilation

Thank you for opening this issue.

Unfortunately the error description was a bit misleading since it copied the typings for FormControl . The focus event handlers being typed there is a bug. They are passed to the div by default i.e. they never fire by default since the element isn’t focusable (and likely shouldn’t be anyway).

As to the TextField : The typings assume that the focus handler are attached to the root component but they’re actually attached to the rendered input. I’m giving it the same treatment as onChange but I can’t promise you that this helps you since I don’t know your usecase.

Источник

What is the TypeScript definition for the onBlur event in React?

Please continue reading below to see how to use it or read my guide on using React events with TypeScript.

You can also go to the search page 🔍 to find another event.

Interface

interface FocusEventT = Element> extends SyntheticEventT, NativeFocusEvent>  relatedTarget: EventTarget | null; target: EventTarget & T; >

Full example

import React,  FocusEvent > from 'react'; const InputComponent = () =>  const handleFocusEvent = (e: FocusEventHTMLInputElement>) =>  // Do something >; return input value="Some text" onBlur=handleFocusEvent> />; >; export default InputComponent;

Attributes that use FocusEvent:

Get notified about new tutorials

Join over 1,000 developers who receive React and JavaScript tutorials via email.

No spam. Unsubscribe at any time.

Источник

React + TypeScript: Handling onFocus and onBlur events

This article walks you through a complete example of handling the onFocus and the onBlur events in a React project that is written in TypeScript.

We are going to use modern React features like hooks and functional components. Therefore, before getting started, make sure your React version is 16.8 or newer.

Overview

The onFocus event occurs when an element or some element inside it gets focus. The onBlur event is the opposite of the onFocus event. It occurs when an element (or some element inside it) loses focus. Both of these events work on all elements in the React DOM but are most often used with form.

The event object has the type like so:

For more clarity, please see the example below.

Complete Example

Preview

This example demonstrates a common task: validating the name entered by a user.

  • When the text field is focused, a hint will show up on the right side to info the user that only letters and spaces are accepted.
  • When the onBlur event occurs, the validation logic will run and an error message will appear if the entered name is invalid. Otherwise, you will see a success message.

You can also see information about the event objects in the console.

The Code

1. Initialize a new React project by running:

npx create-react-app kindacode_example --template typescript

2. Replace all of the unwanted code in your src/App.tsx with the below:

// App.js // Kindacode.com import React, < useState >from "react"; import "./App.css"; const App = () => < const [name, setName] = useState(""); const [isValid, setIsValid] = useState(false); const [isFocus, setIsFocus] = useState(false); const [isBlur, setIsBlur] = useState(false); // Handling input onChange event const changeHandler = (event: React.ChangeEvent) => < setName(event.target.value); >; // Handling input onFocus event const focusHandler = (event: React.FocusEvent) => < setIsFocus(true); setIsBlur(false); // Do something with event console.log(event); >; // Handling input onBlur event const blurHandler = (event: React.FocusEvent) => < setIsFocus(false); setIsBlur(true); // Validate entered name if(name.match(/^[a-z][a-z\s]*$/i))< setIsValid(true); >else < setIsValid(false); >// Do something with event console.log(event); >; return ( 

Please enter your name:

onBlur= value= onChange= className="input" placeholder="Please enter your name" /> Only letters and spaces are acceptable )> The name you entered is not valid

> The name you entered looks good>
); >; export default App;

3. To make the app look better a little bit, remove all the default code in your src/App.css and add the following:

/* App.css Kindacode.com */ .container < padding: 50px; >.input < padding: 8px 10px; width: 300px; font-size: 18px; >.hint < margin-left: 20px; >.error < color: red; >.success

Conclusion

We’ve gone over an example of working with the onFocus and the onBlur events in React and TypeScript. If you’d like to learn more new and interesting things about React, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Источник

React blur event typescript

Last updated: Jan 15, 2023
Reading time · 3 min

banner

# Type the onFocus and onBlur events in React (TypeScript)

Use the React.FocusEvent type to type the onFocus and onBlur events in React. The FocusEvent interface is used for onFocus and onBlur events.

Copied!
import React from 'react'; const App = () => const handleFocus = (event: React.FocusEventHTMLElement>) => console.log(event); >; const handleBlur = (event: React.FocusEventHTMLElement>) => console.log(event); >; return ( div> input type="text" id="message" name="message" defaultValue="" onFocus=handleFocus> onBlur=handleBlur> /> div> ); >; export default App;

We typed the events as React.FocusEvent because the FocusEvent type is used for onFocus and onBlur events in React.

However, we could have been more specific when typing the event.

# The easiest way to find the type of an event

The easiest way for you to find out what the type of an event is, is to write the event handler inline and hover over the event parameter in the function.

Copied!
const App = () => // 👇️ events are written inline // hover over the `event` parameter with your mouse return ( div> input type="text" id="message" name="message" defaultValue="" onFocus=event => console.log(event)> onBlur=event => console.log(event)> /> div> ); >; export default App;

When the event is written inline, I can hover over the event parameter and it shows me what the type of the event is.

TypeScript is able to infer the type of the event when it’s written inline.

This is very useful because it works with all events. Simply write a «mock» implementation of your event handler inline and hover over the event parameter to get its type.

Once you know the type of the event, you are able to extract your handler function and type it correctly.

Now that we know that the correct type for the onFocus and onBlur events in the example is React.FocusEvent , we can extract our handler function.

Copied!
import React from 'react'; const App = () => const handleFocus = (event: React.FocusEventHTMLInputElement, Element>) => console.log(event); >; const handleBlur = (event: React.FocusEventHTMLInputElement, Element>) => console.log(event); >; return ( div> input type="text" id="message" name="message" defaultValue="" onFocus=handleFocus> onBlur=handleBlur> /> div> ); >; export default App;

The type we passed to the FocusEvent generic is HTMLInputElement because we attached the events to an input element, however, you could be attaching the event to a different element.

The types are consistently named HTML***Element . Once you start typing HTML.. , your IDE should be able to help you with autocomplete.

Some commonly used types are: HTMLInputElement , HTMLButtonElement , HTMLAnchorElement , HTMLImageElement , HTMLTextAreaElement , HTMLSelectElement , etc.

Note that you can use this approach to get the type of all events, not just onFocus and onBlur events.

As long as you write the event handler function inline and hover over the event parameter, TypeScript will be able to infer the event’s type.

If you need to check if an element is focused in React, click on the following article.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

What is the TypeScript definition for the onBlurCapture event in React?

The right interface for onBlurCapture is FocusEvent

Please continue reading below to see how to use it or read my guide on using React events with TypeScript.

You can also go to the search page 🔍 to find another event.

Interface

interface FocusEventT = Element> extends SyntheticEventT, NativeFocusEvent>  relatedTarget: EventTarget | null; target: EventTarget & T; >

Full example

import React,  FocusEvent > from 'react'; const InputComponent = () =>  const handleFocusEvent = (e: FocusEventHTMLInputElement>) =>  // Do something >; return input value="Some text" onBlurCapture=handleFocusEvent> />; >; export default InputComponent;

Attributes that use FocusEvent:

Get notified about new tutorials

Join over 1,000 developers who receive React and JavaScript tutorials via email.

No spam. Unsubscribe at any time.

Источник

Оцените статью