Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' }}
     />
like image 422
kacper3671 Avatar asked Oct 22 '25 16:10

kacper3671


1 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
like image 192
Jamal Eddine Naamani Avatar answered Oct 24 '25 06:10

Jamal Eddine Naamani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!