1

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

Evan
  • 1,892
  • 2
  • 19
  • 40
  • you didn't provide where the updateItemHandler callback is used, but anyway, it should be e.target.focus() instead of e.focus() – Guy Perry Oct 03 '21 at 18:22
  • 1
    sorry just updated the code to provide it, thank you - I don't think e.target.focus() will work here since then React will be trying to focus the icon you click on instead of the textbox – Evan Oct 03 '21 at 18:34

1 Answers1

1

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

Nacho
  • 870
  • 6
  • 9
  • hm this seems like it should work perfectly because when I print out ref.current.focus I get the actual HTML element, but for some reason the .focus() call doesn't actually focus it (i.e. put the cursor onto the newly editable textfield). – Evan Oct 03 '21 at 18:32
  • update figured it out, it's due to odd behavior that be overcome with a settimeout: https://stackoverflow.com/a/37162116/11634814 – Evan Oct 03 '21 at 18:41