search
HomeWeb Front-endFront-end Q&AHow to set focus in react

How to set focus in react

Dec 27, 2022 am 11:18 AM
react

How to set focus in react: 1. Use DOM elements in componentDidMount; 2. Call the DOM API of "this.input.focus()" to automatically focus on the input when the page is loaded. box function.

How to set focus in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to set focus in react?

React automatically focuses on an input box after entering the page

How to set focus in react

In React.js, you basically don’t need to deal with the DOM directly. React.js provides a series of on* methods to help us monitor events, so there is no need to directly call the DOM API of addEventListener in React.js; in the past, we updated the page through manual DOM operations (for example, with the help of jQuery), but in React. In js, components can be re-rendered directly through setState. When rendering, new props can be passed to sub-components to achieve the page update effect.

The re-rendering mechanism of React.js helps us avoid most DOM update operations, and also allows third-party libraries like jQuery, which mainly encapsulate DOM operations, to be used as our development tools. Removed from the chain.

But React.js cannot fully meet all DOM operation needs. Sometimes we still need to deal with DOM. For example, if you want to automatically focus on an input box after entering the page, you need to call the DOM API of input.focus(). For example, if you want to dynamically obtain the size of a DOM element for subsequent animation, etc.

React.js provides the ref attribute to help us get the DOM node of the mounted element. You can add the ref attribute to a JSX element.

You can see that we added a ref attribute to the input element, and the value of this attribute is a function. When the input element is mounted on the page, React.js will call this function and pass the mounted DOM node to this function. In the function, we set this DOM element as an attribute of the component instance, so that we can get this DOM element through this.input in the future.

Then we can use this DOM element in componentDidMount and call the DOM API of this.input.focus(). Overall, it achieves the function of automatically focusing on the input box after the page is loaded (you can notice that we use the componentDidMount component life cycle).

We can add ref to any HTML element tag to obtain its DOM element and then call the DOM API. But remember one principle: don’t use ref if you can. In particular, avoid using ref for automatic page update operations and event monitoring that React.js can help you do. Redundant DOM operations are actually "noise" in the code, which is not conducive to our understanding and maintenance.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 进入页面以后自动 focus 到某个输入框</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class AutoFocusInput extends React.Component {
  componentDidMount () {
    this.input.focus()
  }
 
  render () {
    return (
      <input ref={(input) => this.input = input} />
    )
  }
}
ReactDOM.render(
  <AutoFocusInput />,
  document.getElementById(&#39;root&#39;)
);
</script>
</body>
</html>

Another way of writing:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>React 进入页面以后自动 focus 到某个输入框</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
 
    this.inputRef = React.createRef();
  }
 
  render() {
    return <input type="text" ref={this.inputRef} />;
  }
 
  componentDidMount() {
    this.inputRef.current.focus();
  }
}
 
 
ReactDOM.render(
  <MyComponent />,
  document.getElementById(&#39;root&#39;)
);
</script>
</body>
</html>

Recommended learning: "react video tutorial"

The above is the detailed content of How to set focus in react. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)