0

In my component I have valueState which is the value of the text and props.prevRequestState which stores the previous value that was sent using enter key.

My goal is to be able to use the up arrow to display the previous request.

This works but I also want the cursor to be at the end of text when I press the up arrow.

I have troubles figuring how to do that.

import React, { useState, useRef} from 'react';
import Button from '@material-ui/core/Button';
import styles from 'styles/TextForm.module.css';


function TextForm(props) {
  const [valueState, setValueState] = useState('');
  const inputTextRef = useRef();
  
  
  function handleChange(e) {
    setValueState(e.target.value);
  }


  function submitText() {
    props.setBubbleTextState(valueState);
  }

  function handleKeyPress(e) {
    if (e.key === 'Enter') {
      submitText()
      setValueState('');
    }
    if (e.key === 'ArrowUp') {
      setValueState(props.prevRequestState);
    }
  }

  return (
    <div className={styles.container}>
      <input type="text" value={valueState} onChange={handleChange} className={styles.textForm} ref={inputTextRef}
             onKeyDown={handleKeyPress} placeholder='Entrez votre requête.' size='80'/>
      <Button variant="outlined" color="primary" onClick={submitText} className={styles.switchButton}> 
        Envoyer
      </Button>
    </div>
  );

}

export default TextForm;

I understand that using in handleKeyPress(e):

e.input.selectionStart = props.prevRequestState.length
e.input.selectionStop = props.prevRequestState.length

will not work because my valueState is not updated at the time I press the arrow.

Using the old setState callback would work well but here I don't know how to trigger this specific action when the state is updated, but only after this special up-arrow event. I know I need to use a combination of useRef and useEffect but I can't understand the right way to do it.

Thank you in advance

aurelien_morel
  • 314
  • 1
  • 10
  • Check this out: https://stackoverflow.com/questions/2127221/move-cursor-to-the-beginning-of-the-input-field – LUKER Jul 08 '21 at 15:51

0 Answers0