0

First, please look at my code.

I re-write my code to make it clear. So no need to worry about import things!

const test = () => {

    return (

        <label >
             <input type='file' multiple style={{ display: 'none' }} />
             <Tooltip title='Upload Files'>
                 <IconButton>
                     <AddBox color='primary' fontSize='large'/>
                 </IconButton>
             </Tooltip>
        </label>

    )
}

Here, with this code, I'm trying to open input type="text" when I click IconButton.

But seems there is no change.

I tried a few different ways, however it didn't work well :/

FYI, Here is the picture of AddBox button that I want to use on behalf of input type='text'.

ADD ICONBUTTON

I'm not good at English so please be understanding!

I'm looking forward to hearing from you!!

jefi
  • 185
  • 1
  • 13
Aden Lee
  • 230
  • 2
  • 15

1 Answers1

0

Try this

const Test = () => {
  return (
    <label htmlFor='file'>
      <input
        id='file'
        type='file'
        multiple
        style={{ position: 'fixed', top: '-100em' }}
        onChange={e => console.log(e.target.files)}
      />
      <Tooltip title='Upload Files'>
        <IconButton component='span'>
          <RiAddBoxFill color='primary' fontSize='large' />
        </IconButton>
      </Tooltip>
    </label>
  );
};

I created this code based on Material UI example (https://mui.com/components/buttons/#upload-button) and it already tested

Notes :

  1. the htmlFor attribute in label and id in input used to connect both elements to make the label trigger input click if the value matched. See this : https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/for (in plain js we use for but in react we use htmlFor probably because for keyword is reserved for javascript for loop)
  2. IconButton need component='span' props (I'm not sure about this, by default it use button but when I tried it failed to trigger the input click, probably because button element blocking the label element)
  3. EDIT: In Safari, the input gets disabled when hidden with display: none. A better approach would be to use position: fixed; top: -100em. Source: https://stackoverflow.com/a/28075416/10661914

EDIT: to get the files use onChange on the input element, code already updated

Jemika Negara
  • 54
  • 2
  • 5