관리 메뉴

Silver Library (Archived)

[react & JS] console.log, e.target.value 본문

Face the fear, build the future/Revision Sector

[react & JS] console.log, e.target.value

Chesed Kim 2022. 12. 2. 12:00
반응형

리엑트에서나 JS에서나, 방아쇠 역활을 하는 뭔가를 구성할 때가 되면:

 

onChange={(e) => { setWhatever(e.target.value);}} 를 사용하죠. 

 

독학으로 하는 분들이라면 아마 이런 생각을 하셨을 가능성이 있습니다.

저 e 가 event 를 의미하는 것 까지는 알겠는데, 저 target.value 같은 method 는 어느 JS 문법일까? 같이 말이죠. 

 

하지만 방향은 근접했습니다. 그럼 어떻게 할까요? 우리에게는 console.log 가 있습니다.

그리고 짐작 하셨다시피, 이건 mutation 의 일종입니다. 한번 흐름을 타고 가보도록 하죠.

 

#1. console.log(e) 라고 해보세요. 

이걸 이해하려면, 우선 위와 같은 코드가 적용된 코드 파일 스크립트 내에서

onChange={(e) => console.log(e)} 로 바꿔서 실행 해보는 겁니다.

 

그러면 event 목록들이 촥 펼쳐져 나오는 걸 발견할 수 있습니다.

그 list of events 들 중에서, target 이 보일테고, 그 target 을 펼쳐보면 value 가 보일 겁니다.

 

끝입니다. 이렇게 하는 것이죠.

 

예시로 참조하자면 이렇습니다.

import ReactDOM from 'react-dom';

function MyForm() {
  const name = "";

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input 
          type="text" 
          onChange={(e) => (name = e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
import ReactDOM from 'react-dom';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input 
          type="text" 
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));

Reference.

 

what is onChange={(e) => setName(e.target.value)}? in React mean

I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line " onChange={(e) => setName(e.target.value)}&

stackoverflow.com

 

What are the consequences of mutating event.target.value (in React)?

Let's say we are building custom input component. In this component, as an example let's say we want to change the value from a string to a number const CustomInputComponent = ({ onChange, ...rest ...

stackoverflow.com