Home > Software engineering >  How to move the cursor/caret focus to input after rendering the page (to the left side). React.js
How to move the cursor/caret focus to input after rendering the page (to the left side). React.js

Time:01-13

I have a managed input element in my project. I found 2 ways to focus an input: using useRef(null):

import React, { useEffect, useRef, useState } from "react"
import classes from './MainInput.module.css'

const MainInput = () => {
    const [inputValue, setInputValue] = useState('Wanna find out speed?')
    const inputHandler = (event) => {setInputValue(event.target.value)}

    useEffect(()=>{
      inputRef.current.focus()
    },[])
    
    const inputRef = useRef(null)
  return (
    
    <section className={classes.typespace}>
        <div className={classes.wrapper}>
            <input type="text" ref={inputRef}  className={classes.mainInput} 
            value={inputValue} onChange={inputHandler} />
        </div>
    </section>
  )
};

export default MainInput;

and using the autoFocus attribute:

<input type="text" autoFocus className={classes.mainInput} value={inputValue} onChange={inputHandler} />

But both of these methods position the cursor to the right.

And I need the cursor/caret to be at the beginning of the line, as if I'm just starting to type, but at the same time so that the initial inscription does not disappear (in the case of a placeholder, the inscription will disappear)

Here is a screenshot of the input with the focused cursor:

Important detail, I only want to do this with Javascript/React How to make the cursor immediately focus on the left side of the text?

CodePudding user response:

you can achieve it using setSelectionRange

useEffect(()=>{
  inputRef.current.focus();
  inputRef.current.setSelectionRange(0,0);
},[])

CodePudding user response:

Delete null from useRef, it will not help you. Use this:

  inputRef.current.focus();
  inputRef.current.setSelectionRange(0,0);

If the arguments of this function are identical, then the cursor will be after the corresponding letter, if different, then the first number is the beginning of the selection, and the second is the end of the text selection.

Syntax

setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
  • Related