1. input에서 한 글자 입력 후 focus를 잃는 현상

react로 input을 사용하다보면, 가끔 한 글자 입력 후 input의 focus가 사라지는 현상이 발생한다.

이러한 현상의 원인은 100% state의 변경 등으로 인해 해당 Input이 re-render 되기 때문이다

 

State 변경으로 인한 re-render

1. input만 함수 or 컴포넌트로 따로 묶는 경우

export default function Editor() {
	
	const [name, setName] = useState("");
    
    const onChange = (e) => {
    	const {value} = e.target;
        setName(value);
    }
    
    const Input = () => (<input name="name" value={name} onChange={onChange} />)

	// 한 글자 입력할 때마다 state가 변경 -> Input 컴포넌트가 re-render됨 -> focus 잃음
    // input을 아래 return에 바로 넣어줘야 함
	return (
    	<div>
        	<Input/>
        </div>
    )
}

https://stackoverflow.com/questions/42573017/in-react-es6-why-does-the-input-field-lose-focus-after-typing-a-character

 

In React ES6, why does the input field lose focus after typing a character?

In my component below, the input field loses focus after typing a character. While using Chrome's Inspector, it looks like the whole form is being re-rendered instead of just the value attribute of...

stackoverflow.com

 

2. map의 key 값에 함수 값을 주는 경우

key 값으로 nanoid() 등을 주는 경우, state가 변경될 때마다 nanoid()가 새롭게 실행되어 input이 새롭게 re-render 됨 → focus 잃음

 

3. input이 있는 styled-component 객체를 jsx 컴포넌트 안에 선언하는 경우

state가 변경될 때마다 styled-component 변수를 새롭게 선언함 → focus 잃음

https://www.inflearn.com/questions/121968

 

input 한글자 입력후 focus사라지는 현상 - 인프런 | 질문 & 답변

어...아래 에러는 해결했는데  로그인할때 input창에서 한글자 입력하면 focus를 잃어서 다시 입력하려면 input창을 클릭해야하는 현상이 발생하는데  이건 어디서 문제가 발생한 걸까요 제가 보이

www.inflearn.com

 

2. string으로 js object 값에 접근하기 - reduce 사용

const obj = {
  lego: {
    name: "hello",
  },
};

const string = "lego.name";
const result = string.split(".").reduce((acc, cur) => acc[cur], obj); // hello

+ Recent posts