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
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
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} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With