ok so, I have this scenario where I have a functional component which contains a state variable and a corresponding method to update the state variable as per below ..

const [message, setMessage] = useState("Thank You");

const updateMessageText= (userMessage) => {
    setMessage(userMessage)
  }

I am passing the message state variable and updateMessageText callback function (see above) to the mini editor as per below from my parent element

<MyTextEditor
                  message={message}
                  updateMessageText={updateMessageText}
                        
              />

I have created a mini editor which contains another state variable mainMessageText to hold the supplied message value from the parent and a multiline TextFiled using MaterialUI v5 as per below

const [mainMessageText, setMainMessageText] = useState(message);

<TextField
          ref={inputRef}
            id="textMessage"
            name="textMessage"
            label="Message"
            multiline={true}
            rows={6}
            value={mainMessageText}
            onChange={handleChangeText}           
            inputProps={{
              maxLength: 320,
              minLength: 9,
              style: {
                
                lineHeight: "1em",
               
              },
            }}
          />

The handleChangeText method in the above TextField is as per below ...

const handleChangeText = (e) => {
    updateMessageText(e.target.value)
}

Now, the issue what I am facing is, as soon as user types anything in the TextField, the handleChangeText event gets fired (onChange call) and only one char gets updated when the TextField loses focus which forces the user to click back on the TextField. After lots of debugging I notice that this happens due to the function call back which updates the message state variable in the parent though I don't know how to prevent it as this is an important part of the functionality as my parent component needs this updated text to redraw a canvas element.

Any idea on how to seamlessly allow user to update the TextField without loosing and esp retaining the focus where the last cursor was? I already tried several things like use autoFocus property and set it to true though it puts the focus back at the start of the text in the TextField which is not acceptable. Tried to use useRef for the TextField in combination of onBlur() but that didn't do anything.

0

There are 0 best solutions below