How to set focus on an input field after rendering?
You should do it in componentDidMount
and refs callback
instead. Something like this
componentDidMount(){
this.nameInput.focus();
}
class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( <div> <input defaultValue="Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="will focus" /> </div> ); }} ReactDOM.render(<App />, document.getElementById('app'));
<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>
How to focus on dynamically added Input field in react
Since autofocus
is not working, then you can try with setTimeout
.
What I did was to check if openSearchId
is true
Demo
React.useEffect(() => {
if (openSearchId) {
setTimeout(() => {
inputRef.current?.focus();
console.log("focused");
}, 300);
}
}, [openSearchId]);
Does this work for you? You can change the millis of course.
How to set focus on custom input in ReactJS using useRef and react hooks?
You should use React.forwardRef
to pass a ref
to native input
in your custom component:
import React from 'react';
import './Input.scss';
const input = React.forwardRef((props, ref) => (
<input
type={props.inputtype}
className="input"
placeholder={props.hint}
style={{width: props.width}}
ref={ref}
{...props}
/>
));
export default input;
More details:- https://en.reactjs.org/docs/forwarding-refs.html
How to focus an element after re-render with ReactJS
If I use a someCreatedRef.current.focus() command, should that be before or after the setState command?
There is no such order.
but I want to do this after setState is called.
If you want to execute certain changes after setState is called you can do the following.
If you are using class component:
setState method provides a callback function that can be executed after state change has been made.
this.setState({
// set the state variable
},() => {
// add the code to focus on particular element.
});
If you are using hooks:
Just add useEffect hook and add the state variable after which is set, you want to focus, as a dependency
useEffect(() => {
// add the code to focus on particular element.
}, [stateVariable])
how react programmatically focus input
The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this
class MyClass extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
}
focus() {
this.textInput.current.focus();
}
render() {
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Set Focus"
onClick={this.focus}
/>
</div>
);
}
}
Update
From React 16.3 upwards you can use the React.createRef()
API
class MyClass extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focus = this.focus.bind(this);
}
focus() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Set Focus"
onClick={this.focus}
/>
</div>
);
}
}
focus() doesn't set on input field after displaing (use refs)
The issue is that React state updates are asynchronously processed, so in the click handler when you enqueue a state update you are immediately attempting to focus on the input, but since the active
state hasn't updated yet you can't, the dnone
classname hasn't been removed and input made visible yet.
Move the focus logic into the componentDidUpdate
lifecycle method to "respond" to the active
state updating.
componentDidUpdate(prevProps, prevState) {
if (prevState.active !== this.state.active && this.state.active) {
this.input.current.focus();
}
}
click = (e) => {
e.preventDefault();
this.setState({
active: true
});
}
React How to set focus on the input field after adding a new row by using react-table
I used plain JavaScript
to acheive your goal
const setFocus = () => {
//Add id to the table
document.getElementsByTagName("TABLE")[0].setAttribute("id", "mytable");
//table > tbody > tr (latest added row) > td (first cell in the row) > input
let cell = document.getElementById("mytable").lastElementChild
.lastElementChild.firstElementChild.children[0];
cell.focus();
};
const addNew = () => {
setData(old => [...old, {}]);
window.requestAnimationFrame(setFocus);
};
I used requestAnimationFrame
because I was manipulating the DOM, Checkout this answer for more details.
How to focus element based on button click in React.js
You need to have an onClick
event on the div and the call the focus()
function on the input element that you can access by refs
in react:
class App extends React.Component {
render() {
return (
<div>
<div onClick={() => {this.myInp.focus()}}>Focus Input</div>
<input type="text" ref={(ip) => this.myInp = ip} />
</div>
)
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
Set the focus to input after submitting the form
I think you can use DOM.focus() and useRef() to handle
what you looking for:
const inputRef = useRef()
const setTodo = (event) => {
setNewTodo(event.target.value)
}
const handleSubmit = (event) => {
event.preventDefault()
}
const addTodoByEnter = (event) => {
if (event.key === 'Enter') {
if (newTodo.trim() !== '') {
const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length + 1 }
setTodos([...todos, currentTodo])
setNewTodo('')
}
}
}
const addTodoByClick = () => {
if (newTodo.trim() !== '') {
const currentTodo = { id: Date.now(), text: newTodo.trim(), complited: false, order: todos.length + 1 }
setTodos([...todos, currentTodo])
setNewTodo('')
inputRef.current?.focus();
}
}
<div className="input">
<form className="input__form" action="" onSubmit={handleSubmit}>
<input
ref={inputRef}
className="input__add"
type="text"
maxLength={180}
value={newTodo}
onKeyDown={(event) => addTodoByEnter(event)}
onChange={setTodo}
autoFocus />
<button className="input__img" type="submit" onClick={addTodoByClick}></button>
</form>
</div>
Related Topics
What's the Significant Use of Unary Plus and Minus Operators
How to Fire and Forget a Promise in Nodejs (Es7)
How to Bind Fancybox to Dynamic Added Element
How to Find Events Bound on an Element with Jquery
Pass Props to Parent Component in React.Js
Why Was the Arguments.Callee.Caller Property Deprecated in JavaScript
Difference Between Settimeout with and Without Quotes and Parentheses
Allow Google Chrome to Use Xmlhttprequest to Load a Url from a Local File
How to Check If a Checkbox Is Checked
How to Access Iframe Elements with JavaScript
Prevent Execution of Parent Event Handler
Sort Array by Firstname (Alphabetically) in JavaScript
Insert HTML at Caret in a Contenteditable Div
How to Run Gulp Tasks Sequentially One After the Other