본문 바로가기
coding/React

[React] input file 태그 내에서 value 값 설정하기 - Failed to set the 'value' property on 'HTMLInputElement

by 김학준0724 2022. 9. 26.

 

React 파일 태그 사용 간 value 설정 방법을 정리하려고합니다.

 

input file 태그를 사용해 허용된 확장자가 아닌 경우 알람 및 value 초기화 수행하는 코드를 작성했습니다.

 

처음 코드 작성 시 태그 내 value 속성으로 초기화 수행 시 예외 발생으로 동일한 에러 발생되는 분은 코드 참고하세요

Failed to set the 'value' property on 'HTMLInputElement': 

This input element accepts a filename, which may only be programmatically set to the empty string.

 

1. 결과화면

     a.  허용된 확장자(.msg) 파일 첨부 시 

 

    b.  허용된 확장자(.msg) 이외 파일 첨부 시

 

 

 

2. 소스 코드

import React, {  useState } from 'react';

const Enrollment = () => {

	const [attached , setAttached] = useState("")
    
    const onChange_Attached = (e) => {
    
        if(e.target.files[0].name.includes('.msg')){
            setAttached(e.target.files[0] )
        }else{
            alert('fail')
            e.target.value = null;
        }

    }    
    
    return (
        <div>
            <label>Attached :</label>
            <input type="file" accept='.msg' onChange={onChange_Attached} ></input>
        </div>  
    )
}
export default Enrollment;