Home > Software design >  How to clear a Material UI textfield of file type
How to clear a Material UI textfield of file type

Time:02-15

I've tried mutliple approaches, but I cannot seem to clear a Material UI textfield with type="file"

I am limiting the file size, and if a user oversteps the limit, an error message pops up, but the Textfield also needs to be cleared.

Here is my code:

function CreateClaim(props) {

const [supporting_docs, setSupportingDocs] = useState(null);

const handleFileUpload = (event) => {
    event.preventDefault()
    if(event.target.files[0].size > 10971520) {
      setFileError(true)
      setSupportingDocs(null)
    } 
    else {
      setSupportingDocs(event.target.files)
    }
  };

return (

<TextField onChange={handleFileUpload}
   InputLabelProps={{ shrink: true }}
   margin="normal"
   required
   fullWidth
   id="supporting_docs"
   label="Bewys van uitgawe"
   name="supporting_docs"
   type="file"         
   />
)

} export default CreateClaim

The error message works well, but cant clear the Textfield, any suggestions?

CodePudding user response:

You can add this line:

if (event.target.files[0].size > 10971520) {
    setFileError(true);
    setSupportingDocs(null);
    e.target.value = null;
} 

CodePudding user response:

You can try this. If the file is more than 1MB it will show an Error. Click to see preview

const Demo = () => {
  const [error, setError] = useState(false);

  const handleFileUpload = (e) => {
    console.log(e.target.files[0]);
    const file = e.target.files[0];
    if(file.size) return setError(true)
  }
  return(<>
  {error ? <h1 style={{color: 'red'}} >Error</h1> : <TextField 
    onChange={handleFileUpload}
    InputLabelProps={{ shrink: true }}
    margin="normal"
    required
    fullWidth
    id="supporting_docs"
    label="Bewys van uitgawe"
    name="supporting_docs"
    type="file"         
    />}
  </>)
}
  • Related