Set focus on the dynamic input field in React
Today we’ll show you how to set focus on the dynamic input field in React after rendering. Here we will use an existing example and continue on it.
As per the request of our readers, we decided to provide the solution to their query for implementation of the auto focus on the dynamic input field in ReactJS.
Let’s continue with our previous article Add or remove input fields dynamically with ReactJS and enhance the functionality to set auto focus.
Steps to set auto focus on the input field after render
- Implement demo to add or remove input fields dynamically
- Manage an input reference in the state variable
- Set the focus on the dynamic input field
- Output
1. Implement demo to add or remove input fields dynamically
First, create a demo to add or remove input fields dynamically in React. Use the following article for more information.
Add or remove input fields dynamically with ReactJS
2. Manage an input reference in the state variable
Now, let’s assume that we need to set the focus on the firstName
when we add/remove input dynamically.
For that, we have to take the one more variable in the inputList
for an input reference. Also delete that variable to avoid the error while displaying on the page using JSON.stringify()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | return ( <div className="App"> <h3><a href="https://cluemediator.com">Clue Mediator</a></h3> {inputList.map((x, i) => { return ( <div className="box"> <input name="firstName" placeholder="Enter First Name" value={x.firstName} ref={e => x.firstNameRef = e} onChange={e => handleInputChange(e, i)} /> ... ... </div> ); })} <div style={{ marginTop: 20 }}>{JSON.stringify(inputList.map(x => { delete x.firstNameRef; return x; }))}</div> </div> ); |
3. Set the focus on the dynamic input field
In the next step, we have to set the focus on the dynamic input field also we are adding one more variable firstNameRef
in state object for an input reference. Check out the below code.
1 2 3 4 5 6 7 8 9 10 11 12 | const [inputList, setInputList] = useState([{ firstName: "", lastName: "", firstNameRef: null }]); // handle click event of the Add button const handleAddClick = () => { setInputList([...inputList, { firstName: "", lastName: "", firstNameRef: null }]); }; // set focus on the dynamic input field useEffect(() => { if (inputList[inputList.length - 1].firstNameRef) inputList[inputList.length - 1].firstNameRef.focus(); }, [inputList.length]); |
4. Output
Let’s combine all code together and see how it looks.
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | import React, { useState, useEffect } from "react"; function App() { const [inputList, setInputList] = useState([{ firstName: "", lastName: "", firstNameRef: null }]); // handle input change const handleInputChange = (e, index) => { const { name, value } = e.target; const list = [...inputList]; list[index][name] = value; setInputList(list); }; // handle click event of the Remove button const handleRemoveClick = index => { const list = [...inputList]; list.splice(index, 1); setInputList(list); }; // handle click event of the Add button const handleAddClick = () => { setInputList([...inputList, { firstName: "", lastName: "", firstNameRef: null }]); }; // set focus on the dynamic input field useEffect(() => { if (inputList[inputList.length - 1].firstNameRef) inputList[inputList.length - 1].firstNameRef.focus(); }, [inputList.length]); return ( <div className="App"> <h3>Set focus on the dynamic input field - <a href="https://cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h3> {inputList.map((x, i) => { return ( <div className="box"> <input name="firstName" placeholder="Enter First Name" value={x.firstName} ref={e => x.firstNameRef = e} onChange={e => handleInputChange(e, i)} /> <input className="ml10" name="lastName" placeholder="Enter Last Name" value={x.lastName} onChange={e => handleInputChange(e, i)} /> <div className="btn-box"> {inputList.length !== 1 && <button className="mr10" onClick={() => handleRemoveClick(i)}>Remove</button>} {inputList.length - 1 === i && <button onClick={handleAddClick}>Add</button>} </div> </div> ); })} <div style={{ marginTop: 20 }}>{JSON.stringify(inputList.map(x => { delete x.firstNameRef; return x; }))}</div> </div> ); } export default App; |
That’s it for today.
Thank you for reading. Happy Coding..!!
Thanks much.. I have query might be a basic one..so, is it not necessary to use a createRef to be used as ref in Input component.? Thanks.
It would be a good practice if you could use it.