Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how get get file name in file chooser in react?

could you please tell me how get get file name in file chooser in react ? I am trying to set value in input field after choosing file from file chooser here is my code https://stackblitz.com/edit/react-d4kp1d?file=bulk.js I tried like this

<input
        id="file_input_file"
        className="none"
        type="file"
        ref={inputRef }
        onChange={(e)=>{
          console.log('---')
          console.log(inputRef.current[0].files[0].name)

        }}
      />

it gives me undefined

like image 434
user944513 Avatar asked Mar 21 '19 23:03

user944513


2 Answers

Good documentation and example taken from here, explaining what you are trying to do. https://reactjs.org/docs/uncontrolled-components.html#the-file-input-tag

Codepen: https://codepen.io/anon/pen/LaXXJj

React.JS contains a specific File API to use.

The following example shows how to create a ref to the DOM node to access file(s) in a submit handler:

HTML

<input type="file" />

React.JS

class FileInput extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.fileInput = React.createRef();
  }
  handleSubmit(event) {
    event.preventDefault();
    alert(
      `Selected file - ${
        this.fileInput.current.files[0].name
      }`
    );
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Upload file:
          <input type="file" ref={this.fileInput} />
        </label>
        <br />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

ReactDOM.render(
  <FileInput />,
  document.getElementById('root')
);

Alert Filename

alert(`Selected file - ${this.fileInput.current.files[0].name}`);

Cited: React.JS Documentation | Examples

like image 126
ABC Avatar answered Sep 22 '22 13:09

ABC


You can get selected file name without using ref

  function handleChange(event) {
    console.log(`Selected file - ${event.target.files[0].name}`);
  }

  <input type="file" onChange={handleChange} />


like image 30
Yusufbek Avatar answered Sep 22 '22 13:09

Yusufbek