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' }}
     />
Beso
  • 1,176
  • 5
  • 12
  • 26
kacper3671
  • 136
  • 1
  • 3
  • 11

2 Answers2

4

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
hiddensunset4
  • 5,825
  • 3
  • 39
  • 61
  • 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) – nonemaw Aug 10 '23 at 13:04
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

Benji
  • 15
  • 4