4

How can I open an file input with a button click ? My code :

<Button variant="outlined">
      Choose Image
    </Button>
     <input
      type="file"
      id="input_file"
      accept=".jpg,.jpeg,.png"
      style={{ display: 'none' }}
     />
2
  • To clarify: you want the browser to pop up windows explorer so the user chan a choose a file to upload when the button is clicked? Commented Sep 24, 2021 at 11:31
  • Yes, this i what i want Commented Sep 27, 2021 at 7:13

2 Answers 2

5

React >= 16.8 , using useRef hook

import React, { useRef } from 'react'

const MyComponent = () => {
  const ref = useRef()
  const handleClick = (e) => {
    ref.current.click()
  }
  return (
    <>
      <button onClick={handleClick}>Upload Image</button>
      <input ref={ref} type="file" />
    </>
  )
}

export default MyComponent
Sign up to request clarification or add additional context in comments.

1 Comment

It works on my scenario perfectly: use ref to trigger file upload window from an image's click event, really thanks! (I wasted almost whole day on this)
0
  const Open = () => { 
    document.getElementById('get_file').onclick = function() { 
      document.getElementById('input_file').click();}}

    <button id="get_file" variant="outlined" onClick={() => Open() } > Choose Image </button> 
    <input type="file" id="input_file" accept=".jpg,.jpeg,.png" style={{ display: 'none' }} />

You have a answer here How to link an input button to a file select window

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.