Amar Thapa
Amar Thapa

Reputation: 61

How to make input `type=file` to accept only images React

<Input
  id="image"
  type="file"
  accept="image/*"
  onChange={(event) =>
    getBase64(event.target.files[0])
      .then((file) => this.setState({ image: file })
  )}
/> 

But it does accept other files too, what should I change to make it accept only images?

Upvotes: 6

Views: 23170

Answers (4)

Rishabh kadam
Rishabh kadam

Reputation: 21

<input type="file" accept="image/*" />

this make input image only

Upvotes: 0

Mafei
Mafei

Reputation: 3799

The problem may be that you have passed or modified the props after changed the accept attribute. so, you have a solution or that. change the attribute order you passed. that means you can pass the accept attribute as the last attribute, like below.

<Input
 id="image"
 type="file"
 onChange={event =>
  getBase64(event.target.files[0]).then(file =>
   this.setState({ image: file })
 )
 accept="image/*"
}
/> 

Upvotes: 2

Clint
Clint

Reputation: 463

To set the accept attribute on an <Input /> you need to use inputPropslike this

<Input type="file" inputProps={{ accept: 'image/*' }} />

EDIT Looking at this some months later and reading @Aprillions comment I think it would be good to clarify this is Material-UI and not pure React

Upvotes: 6

OliverRadini
OliverRadini

Reputation: 6466

File inputs have an accept attribute which you can use for this (docs).

Upvotes: 1

Related Questions