# onInput

## Input Event

input 이벤트는 \<input>, \<select>, \<textarea>의 value 속성이 바뀔 때마다 발생한다. 따라서 react에서 이벤트를 처리하기 위해서는 이벤트 대상 정보가 필요하다.

## 이벤트 설정 방법

이벤트는 JSX에 다음과 같이 작성하여 설정한다.

```jsx
function tempFunc(e){
    //e.target : 대상 태그 객체
    //e.target.value : 대상 태그에 입력된 값
}

app.render(
    <input onInput={tempFunc}/>
);
```

{% hint style="info" %}
input 태그와 같이 닫히는 태그가 없는 경우에도 JSX에서는 반드시 <mark style="color:red;">**종료 처리**</mark>를 해야 한다.

* \<input>\</input>
* \<input/>
  {% endhint %}

## 예제 - 입력 글자 수 카운트

```jsx
let text = "";
function setText(e){
    text = e.target.value;
    startRendering();
}

const app = ReactDOM.createRoot(document.querySelector("#app"));
function startRendering(){
    app.render(
        <div>
            <input type="text" onInput={setText}/>
            <span>{text.length}</span>
        </div>
    );
};
startRendering();
```

{% embed url="<https://codepen.io/hiphop5782/pen/GRGRZzX>" %}

{% hint style="info" %}

### this 사용 주의사항

```jsx
function setText(e){
    text = e.target.value;//정상 코드
    startRendering();
}
```

vanillaJS나 jquery에서는 this를 사용하여 value를 불러올 수 있으나, react에서 다음 코드는 사용할 수 없다.

```jsx
function setText(e){
    text = this.value;//사용 불가
    startRendering();
}

```

{% endhint %}

## 예제 - 닉네임 검사(정규표현식)

```jsx
let nickname = "";
function setNickname(e){
    nickname = e.target.value;
    startRendering();
}

const regex = /^[가-힣0-9]{2,10}$/;
const app = ReactDOM.createRoot(document.querySelector("#app"));
function startRendering(){
    //닉네임의 상태에 따라 다른 화면을 렌더링
    let resultSpan;
    if(nickname.length == 0){
        resultSpan = <span></span>
    }
    else {
        const judge = regex.test(nickname);
        if(judge){
            resultSpan = <span>멋진 닉네임입니다!</span>
        }
        else {
            resultSpan = <span>닉네임은 한글과 숫자 2~10글자로 작성해주세요</span>
        }
    }

    app.render(
        <div>
            <input type="text" onInput={setNickname}/>
            {resultSpan}
        </div>
    );
};
startRendering();
```

{% embed url="<https://codepen.io/hiphop5782/pen/mdKdPYG>" %}

점점 코드가 길어지면서 가독성이 떨어지는 것을 확인할 수 있다. 이러한 비효율성을 개선하기 위하여 클래스형 컴포넌트나 함수형 컴포넌트를 사용할 필요가 있다.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sysout.co.kr/web/develop-page/js/reactjs/cdn/handling-events/oninput.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
