Front-end

e.preventDefault 사용 이유

SONIHEEE 2023. 7. 22. 11:35

코드를 짜다보면 e.preventDefault()를 사용할때가 많다

하지만 이유는 모름

다들 사용하니까 그냥 사용하는 느낌....그래서 갑자기 왜 사용하는지 궁금해져서 알아봤다

 

a 태그나 submit 태그 같은 경우 클릭하면 href를 통해 이동하거나 새로고침하여 페이지가 열리게 되는데

preventDefault를 사용하면 위와같은 경우를 막아줄수가 있다...!

 

1. a태그를 눌렀을때에도 링크로 이동하지 않게 하고싶은 경우

2. form 안에 submit 역활을 하는 버튼을 눌러도 새로고침을 하고싶지 않은 경우

 

2의 경우 예시

 

              constructor(props){
                    super(props);
                    this.state = {
                        first: Math.ceil(Math.random() * 9),
                        second: Math.ceil(Math.random() * 9),
                        value: '',
                        result: '',
                    };
                }

                onSubmit = (e) => {
                    if(parseInt(this.state.value) === this.state.first * this.state.second){
                        this.setState({
                            result: `정답 : ${this.state.value}`,
                            first: Math.ceil(Math.random() * 9),
                            second: Math.ceil(Math.random() * 9),
                            value: '',
                        });
                    } else {
                        this.setState({
                            result: '떙',
                            value: '',
                        });
                    }
                };

                onChange = (e) => this.setState({value: e.target.value});

위의 코드의 경우 onSubmit을 하면 result가 잠시 화면에 나왔다가 사라지게 된다!

preventDefault를 해주지 않았기 때문에...!! submit을 함과 동시에 창이 다시 실행되기 때문에 result가 잠시 화면에 나왔다가 초기화면으로 돌아가게 되는것

 

 		onSubmit = (e) => {
                    e.preventDefault();
                    if(parseInt(this.state.value) === this.state.first * this.state.second){
                        this.setState({
                            result: `정답 : ${this.state.value}`,
                            first: Math.ceil(Math.random() * 9),
                            second: Math.ceil(Math.random() * 9),
                            value: '',
                        });
                    } else {
                        this.setState({
                            result: '떙',
                            value: '',
                        });
                    }
                };

위의 코드처럼  e.preventDefault(); 를 써주면 submit과 동시에 새로 이동되는 것을 막아주기때문에

result가 제대로 화면에 표시되게 된다!

 

비슷한 함수로는 stopPropagation가 있다 이 함수는 부모태그로 이벤트를 전파하는것을 막아준다

이거는 다음에 알아보는걸로~~~~ 🫥🫥

'Front-end' 카테고리의 다른 글

공공데이터포털 API연결  (0) 2023.09.17
REST API  (1) 2023.08.15
react-router-dom  (0) 2023.07.08
프레임워크 / 라이브러리 / 플러그인  (0) 2023.07.06
solidjs란  (0) 2023.06.21