To move focus to a newly created element, you can store the element's ID in the state and use it to set autoFocus. e.g. React 16.3 added a new convenient way to handle this by creating a ref in component's constructor and use it like below: If you just want to focus an element when it mounts (initially renders) a simple use of the autoFocus attribute will do. @Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:
componentDidMount() {
this.nameInput.focus();
}
@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:
< input autoFocus name = ...
You should do it in componentDidMount
and refs callback
instead. Something like this
componentDidMount() {
this.nameInput.focus();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>
Step 2: After creating your project folder i.e. foldername, move to it using the following command: Step 1: Create a React application using the following command: Step to Run Application: Run the application using the following command from the root directory of the project: Setting focus on an input field after rendering in ReactJS can be done in the following ways, but before doing that, set up your project structure with the following steps:
Creating React Application:
npx create - react - app foldername
cd foldername
Project Structure: It will look like the following.
Approach 1: we can do it in componentDidMount() function and refs callback. For example:
componentDidMount() {
this.nameInput.focus();
}
Approach 2: If we just want to focus on an element when it mounts (initially renders) a simple use of the autoFocus attribute will do. we can use the autoFocus prop to have an input automatically focus when mounted.
Filename: App.js
import React, { Component } from "react";
class App extends Component {
render() {
return(
<div>
<input
defaultValue="It Won't focus"
/>
<input autoFocus
defaultValue="It will focus"
/>
</div>
);
}
}
export default App;
Approach 3: We can use the below syntax using the inline ref property.
<input ref={input => input && input.focus()}/>
In this article, we will learn how to set focus on an element after rendering our React application or a React component. This is going to work in our React applications as well. Still, when we want to set focus on an element after rendering with more programmatic control - we can make use of the useEffect() hook in functional components and the componentDidMount() lifecycle method in class components. In this article, we have learned how to set an element to focus using an input field once our application or component renders in both the Class and Functional components. Both methods are the same but have different syntax since they are two different types of components.
In traditional HTML, it was easy to set an element to focus using the autofocus
attribute within our <input>
tag, which is a boolean attribute and is by default set to false
. It instructs the browser to focus on that specific input field, and the user can begin entering values immediately:
<form>
<input type="text" autofocus> // Will focus
<input type="text"> // Won't focus
</form>
Suppose we have a form with two fields, and we want one of the fields to be set on focus after the component renders:
const App = () => {
return (
<div className='container'>
<form>
<input type="text" placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
Let's get started by getting a reference to the input using the useRef()
React hook. To do this, we would first import useRef()
from React, create a ref
and set its value to null by default then and then attach the created ref
to our React element via the ref
attribute:
import { useRef } from 'react';
const App = () => {
const inputReference = useRef(null);
return (
<div className='container'>
<form>
<input type="text" ref={inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
In the code above, notice that we imported the useEffect()
hook and then made use of the hook with an empty dependency array ([]
) to make sure it only fires when the component initially mounts. Finally, to make the referenced element focus, we will access the ref via the current
attribute and then attach the focus()
method:
useEffect(() => {
inputReference.current.focus();
}, [])
At this point, when our application or component renders, the referenced element will automatically be focused:
import { useRef, useEffect } from 'react';
const App = () => {
const inputReference = useRef(null);
useEffect(() => {
inputReference.current.focus();
}, []);
return (
<div className='container'>
<form>
<input type="text" ref={inputReference} placeholder='This has focus' />
<input type="text" placeholder='No focus when we render' />
</form>
</div>
)
}
export default App;
To focus it when the component renders, we have to use React Hook useEffect, which gets called when particular state variable changes, or we can give an empty array to make sure it renders only once when the component renders. Here, the inputRef is the variable that will store the reference for the input type=”text” /> element. To access this, we need to use a current keyword like inputRef.current, and as we have to tell React to focus on this, we can just use focus() method inside the useEffect Hook. Now, to point to a particular JSX element, we need to give it a reference with the useRef Hook of React. Here it is input type=”text” />, an aspect that will be focused on after rendering that page/component.
The autofocus attribute of the HTML <input> tag is a boolean attribute.
The default value of this is false, but if we mention this, it tells the browser to focus on that particular input field, and the user can directly start entering values.
<html>
<body>
<h1>The autofocus attribute</h1>
<form>
<label for="username">Username:</label>
<input type="text" id="uname" name="uname" autofocus> //Will be focused
<br><br>
<label for="email">Email:</label>
<input type="text" id="email" name="email"> //Won't be focused
</form>
</body>
</html>
To create a project, open Command Prompt or PowerShell to the folder where you want to create a project.
Step 1: Create a project of name auto-focus-test
npx create - react - app auto - focus - test
Step 2: Go to created project folder auto-focus-test
cd auto - focus - test
import React, { useEffect } from 'react';
export default function App() {
useEffect(() => {
// Instruction we give here will render once component gets rendered
}, []);
return (
<div className="App">
<label>Email: </label>
<input id="name" />
</div>
);
}
import { useRef, useEffect } from 'react';
export default function App() {
const inputRef = useRef();
useEffect(() => {
// Instruction we give here will render once component gets rendered
}, []);
return (
<div className="App">
<label htmlFor="name">Name: </label>
<input id="name" ref={inputRef} />
</div>
);
}
Now, to point to a particular JSX element, we need to give it a reference with the useRef Hook of React. Here it is input type=”text” />, an aspect that will be focused on after rendering that page/component. Here, the inputRef is the variable that will store the reference for the input type=”text” /> element. To access this, we need to use a current keyword like inputRef.current, and as we have to tell React to focus on this, we can just use focus() method inside the useEffect Hook. The autofocus we did in HTML can also be done in ReactJS, but before going further, we need to create a React project and look into the project structure to relate with what/where you have to implement in your project to use autofocus.
The autofocus attribute of the HTML <input> tag is a boolean attribute.
The default value of this is false, but if we mention this, it tells the browser to focus on that particular input field, and the user can directly start entering values.
<html>
<body>
<h1>The autofocus attribute</h1>
<form> <label for="username">Username:</label> <input type="text" id="uname" name="uname" autofocus> //Will be focused /\n/g/\n/g <label for="email">Email:</label> <input type="text" id="email" name="email"> //Won't be focused</form>
</body>
</html>
To create a project, open Command Prompt or PowerShell to the folder where you want to create a project.
Step 1: Create a project of name auto-focus-test
npx create - react - app auto - focus - test
Step 2: Go to created project folder auto-focus-test
cd auto - focus - test
To focus it when the component renders, we have to use React Hook useEffect, which gets called when particular state variable changes, or we can give an empty array to make sure it renders only once when the component renders.
import React, { useEffect } from 'react'; export default function App() { useEffect(() => { // Instruction we give here will render once component gets rendered}, []); return ( <div className="App"> <label>Email: </label> <input id="name" /> </div> );}
import { useRef, useEffect } from 'react'; export default function App() { const inputRef = useRef(); useEffect(() => { // Instruction we give here will render once component gets rendered }, []); return ( <div className="App"> <label htmlFor="name">Name: </label> <input id="name" ref={inputRef} /> </div> );}
When the other element is clicked, focus the input, e.g. ref. current. focus() . We used the focus() method to focus the input field in the handleClick function.To focus input when another element is clicked in React: To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.20-May-2019
We’ll attempt to use programming in this lesson to solve the How To Set Focus On An Input Field After Rendering? puzzle. This is demonstrated in the code below.
componentDidMount() {
this.nameInput.focus();
}
The focus method is a side effect in React because it is a native HTML API that needs to be called on the HTML DOM and not the virtual DOM. To do that, we need to use refs. The React autoFocusprops are modeled after the HTML autofocus property, which sets focus on the element it is attached to as soon as the page containing that element loads. We used setTimeout in the displayModal function to wait until the input is properly visible after the setShowModal call, before calling focus on it. Else, it won’t work. This method is great for cases where you need to set focus on an input conditionally.
The autoFocus
prop is useful for cases where such input or the form containing the input is the main attraction of the page, like the Google search homepage or a sign-up/sign-in page.
import React, {
Component
} from "react";
const PageWithForm = () => {
return (
);
}
export default PageWithForm;
This method is great for cases where you need to set focus on an input conditionally.
For example, when a button is clicked to display a ‘subscribe to our newsletter’ modal containing an email input:
import React, {
useState,
useRef
} from "react";
const PageWithForm = () => {
const inputElement = useRef(null);
const [showModal, setShowModal] = useState(false);
const displayModal = () => {
setShowModal(true);
setTimeout(() => {
inputElement.current && inputElement.current.focus()
}, 1);
}
return (
Subscribe {
showModal &&
}
);
};
export default PageWithForm;
Note: You can also use the focus
method to set focus on an input just after the page is mounted, like in the first example using the useEffect
hook:
useEffect(() => {
if (inputElement.current) {
inputElement.current.focus();
}
}, []);
Our first step will be getting a reference to the input DOM element. We can do this by using the useRef hook: Great! We now have a reference to our input. But how do we set the focus on it on render? And there you have it! The input will now automatically be focused when the component renders. When a component renders, you may need to automatically set focus on an input. In this post, we look at how we can quickly accomplish this.
export default function App() {
return (
<div className="App">
<label htmlFor="name">Name: </label>
<input id="name" />
</div>
);
}
import { useRef } from 'react';
export default function App() {
const inputRef = useRef();
return (
<div className="App">
<label htmlFor="name">Name: </label>
<input id="name" ref={inputRef} />
</div>
);
}
import { useRef, useEffect } from 'react';
export default function App() {
const inputRef = useRef();
useEffect(() => {
// Focus here
}, []);
return (
<div className="App">
<label htmlFor="name">Name: </label>
<input id="name" ref={inputRef} />
</div>
);
}
The ComponentDidMount() method is the best place to set a focus on the input element. Next, we invoked this.searchInput.focus() method inside the componentDidMount(), so when a component is rendered to the dom it add a focus to the input element. In the above example, we have use class-based react components. let’s see how can we set a focus to the input element using the react hooks. In react, we have the ComponentDidMount() lifecycle method where it runs when a component is mounted to the dom tree.
import React,{Component} from 'react';
class App extends Component {
componentDidMount() {
this.searchInput.focus(); }
render() {
return (
<div>
<label>Search </label>
<input ref={inputEl => (this.searchInput = inputEl)} /> </div>
);
}
}
import React, { useEffect, useRef } from "react";
function App() {
const searchInput = useRef(null);
useEffect(()=>{
// current property is refered to input element
searchInput.current.focus(); },[])
return (
<div>
<label>Search </label>
<input ref={searchInput} /> </div>
);
}
import React, { useEffect, useRef } from "react";
function App() {
const searchInput = useRef(null)
function handleFocus(){
searchInput.current.focus()
}
return (
<div>
<label>Search </label>
<input ref={searchInput} />
<button onClick={handleFocus}>Set focus</button> </div>
);
}