1

I am new to React and javascript want to create a link with name "Browse" which when clicked should take file as input , i got many answers to do it inside class component in React, how can i do it in function component . I tried:

<div>
     <br /><span>{i18n.gettext('- or - ')}</span>
     <input id='logo-input' ref='logoInput' type='file' onChange={onFileSelected} type='hidden' />
     <a href='' onClick={handleBrowse}>{ i18n.gettext('Browse')}</a>
     <br />
</div>

handleBrowse function:

const handleBrowse = function(e) {
        e.preventDefault();
        this.refs.logoInput.click();
    };

onFileSelected function:

const onFileSelected = function (e) {
        const file = e.dataTransfer ? e.dataTransfer.files[0] : e.currentTarget.files[0];
        handleFileSelection(file);
    };

when i do it , i get error as:

Stateless function components cannot have refs

I understood that function component cannot have refs, how can i implement this then

1 Answer 1

3

if you rewrite your component as a class, maybe this error will be gone

class MyComponent extends React.Component{

    handleBrowse =(e) => {
        e.preventDefault();
        this.refs.logoInput.click();
    };

    onFileSelected = (e) => {
        const file = e.dataTransfer ? e.dataTransfer.files[0] : e.currentTarget.files[0];
        handleFileSelection(file);
    };

  render(){
     return (
       <div>
         <br /><span>{i18n.gettext('- or - ')}</span>
         <input id='logo-input' ref='logoInput' type='file' onChange={onFileSelected} type='hidden' />
         <a href='' onClick={this.handleBrowse}>{ i18n.gettext('Browse')}</a>
       <br />
      </div>
     )
  }
}

As a stateless component, this should work like this :

const App = ()=>{

  let myref = null;

  const onFileSelected = (e)=>{
    e.preventDefault();
    console.log(e)
  }

  const handleBrowse = function (e) {
    e.preventDefault();
    myref.click();
  };

   return (
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
        <input id='logo-input' ref={(r) => {myref=r}} type='file' onChange={onFileSelected} />
        <a onClick={handleBrowse}>{ i18n.gettext('Browse')}</a>
      </div>
    );

}
Sign up to request clarification or add additional context in comments.

2 Comments

probably will have to do it, but as it is in prod want to try it with minimal change, not worried about error want if could be done in any other way in function component
Perfect, Thanks

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.