4

In react

const allInputs = { imgUrl: '' };
const [imageAsFile, setImageAsFile] = useState('');
const [imageAsUrl, setImageAsUrl] = useState(allInputs);
const [media, setMedia] = useState(null);

const handleImageAsFile = (e) => {
    const image = e.target.files[0]
    setImageAsFile(imageFile => (image));
    console.log(imageAsFile);

}

Here is the input code, when I click this button, all types of files show, but I want to be able to store the type of file it is in a variable

<input type="text"
    id="phone"
    onChange={(e) => setPhone(e.target.value)}
/>

For example, if I select an image, how can know the type of image I have selected? If it is png or jpg or whatever before uploading it to the database.

9
  • 2
    I think this can help stackoverflow.com/questions/18299806/… Commented Dec 24, 2020 at 13:50
  • Javascript used in react is not the same with the one used for normal html, css and js Commented Dec 24, 2020 at 13:52
  • is there an answer that uses hooks in react Commented Dec 24, 2020 at 13:53
  • That's something of a new concept you've introduced, You should let javascript run the way it runs Commented Dec 24, 2020 at 13:53
  • There's no reason to add hooks in the code to find the type of image, it is completely unncessary. Commented Dec 24, 2020 at 13:55

1 Answer 1

3

First, React Javascript works the exact way Javascript works everywhere, For accessing the image type refer to the below code, I have added the comments for better understanding.

const [imageAsFile, setImageAsFile] = useState('');
    const [imageAsUrl, setImageAsUrl] = useState(allInputs);
    const [media, setMedia] = useState(null);

 const handleImageAsFile = (e) => {
     //image var holds the file object which has a type property 
      const image = e.target.files[0];          
      console.log(image.type); // this will output the mime, i.e "image/png" or "image/jpg"
      setImageAsFile(imageFile => (image));
     console.log(imageAsFile);

  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.