Search code examples
reactjsinputfocus

How to set focus on inputfield in react.js?


How do I set focus on the last added inputfield?

I found a few examples at the www, but all with class-component, not hook.

I did try useref, but I cant make it work.

import React, { useState } from 'react';

const About = () => {
    const [list, setList] = useState([
        { id: 1, txt: 'text 1' },
        { id: 2, txt: 'text 2' }
    ]);

    return (
        <div className="about">
            <h2>About</h2>

            {list.map((elm) => (
                <input key={elm.id} type="text" defaultValue={elm.txt} />
            ))}

            <button value="ADD" onClick={e => {
                e.preventDefault();
                setList(oldList => ([
                    ...oldList, { id: 3, txt: 'text 3', active: true }
                ]));
            }}>ADD</button>

        </div >
    )
}

export default About;

Solution

  • Callback seems to do it.

    import React, { useState, useCallback } from 'react';
    
    const About = () => {
        const [list, setList] = useState([
            { id: 1, txt: 'text 1' },
            { id: 2, txt: 'text 2' }
        ]);
    
        const callbackRef = useCallback(inputElement => {
            if (inputElement) {
                inputElement.focus();
            }
        }, []);
    
        return (
            <div className="about">
                <h2>About</h2>
    
                {list.map((elm) => (
                    elm.active ? <input key={elm.id} type="text" defaultValue={elm.txt} ref={callbackRef} />
                        : <input key={elm.id} type="text" defaultValue={elm.txt} />
                ))}
    
                <button value="ADD" onClick={e => {
                    e.preventDefault();
                    setList(oldList => ([
                        ...oldList, { id: 3, txt: 'text 3', active: true }
                    ]));
                }}>ADD</button>
    
            </div >
        )
    }
    
    export default About;