How to open an <input type="file"/> with a button click in React

Viewed 1711

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 Answers

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
  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

Related