diff --git a/content/docs/forms.md b/content/docs/forms.md index f85cd6f32d6..b3af610a9f5 100644 --- a/content/docs/forms.md +++ b/content/docs/forms.md @@ -189,6 +189,46 @@ Overall, this makes it so that ``, ``, and ````js > >``` +## The file input Tag + +In HTML, a `` lets the user choose one or more files from their device's storage, allowing the app to handle them as per the use case. + +```html + +``` + +In React, a `` works similarly to a normal `` with some major differences. The `` in React is read-only and hence setting the value of a file programmatically is impossible. You can use the various File management API provided by Javascript to handle the files that are uploaded by the user. + +```javascript{7-10,17} +class FileInput extends React.Component { + constructor(props) { + super(props); + this.handleSubmit = this.handleSubmit.bind(this); + } + + handleSubmit (event) { + event.preventDefault(); + alert(`Selected file - ${this.fileInput.files[0].name}`); + } + + render() { + return ( + + + Upload file: + {this.fileInput = input}} /> + + + Submit + + ); + } +} +``` + +[Try it on CodePen](codepen://components-and-props/input-type-file) + +Note how a `ref` to the file input is used to access the file(s) in the submit handler ## Handling Multiple Inputs diff --git a/examples/components-and-props/input-type-file.js b/examples/components-and-props/input-type-file.js new file mode 100644 index 00000000000..18f2c6f1d59 --- /dev/null +++ b/examples/components-and-props/input-type-file.js @@ -0,0 +1,26 @@ +class FileInput extends React.Component { + constructor(props) { + super(props); + this.handleSubmit = this.handleSubmit.bind(this); + } + + handleSubmit (event) { + event.preventDefault(); + alert(`Selected file - ${this.fileInput.files[0].name}`); + } + + render() { + return ( + + + Upload file: + {this.fileInput = input}} /> + + + Submit + + ); + } +} + +ReactDOM.render(, document.getElementById('root'));