javascriptreactjsreact-hookscontenteditablesetfocus

React how to focus div when contentEditable is set to true?


I've got some react code like the following (minimal reproducible example):

import React, { useState } from 'react';

const Todo = ({todo}) => {
    const [isUpdating, setisUpdating] = useState(false)

    const updateItemHandler = (e) => {
        setisUpdating(true);
    }

    return(
        <div onClick={updateItemHandler} className={fa ${isUpdating ? "fa-check" : "fa-pencil"}`}></div>
        <div id={todo.id}>
            <div suppressContentEditableWarning={true}
             contentEditable = {isUpdating}>{todo.value}
            </div>
        </div>
    )
}

export default Todo;

When I clicked the div, it does change contentEditable to true, but I would also like to focus the newly editable div at the same time. I tried modifying my updateItemHandler function like so:

    const updateItemHandler = (e) => {
        setisUpdating(true);
        e.focus();
    }

but React threw an error/said focus wasn't a function here.

Is there some way I can automatically focus the div when I change the contentEditable to true?

Thanks


Solution

  • You can try something like this

    import React, { useState, useRef } from 'react';
    
    const Todo = ({todo}) => {
        const ref = useRef(null)
        const [isUpdating, setisUpdating] = useState(false)
    
        const updateItemHandler = (e) => {
            setisUpdating(true);
            ref.current.focus()
        }
    
        return(
            <div className="row text-center" id={todo.id}>
                <div suppressContentEditableWarning={true}
                 contentEditable = {isUpdating} ref={ref}>{todo.value}
                </div>
            </div>
        )
    }
    
    export default Todo;

    Using ref (reference) may help you