Skip to content

gatsby-remark-code-repls-modification #455

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions content/docs/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,46 @@ Overall, this makes it so that `<input type="text">`, `<textarea>`, and `<select
>```js
><select multiple={true} value={['B', 'C']}>
>```
## The file input Tag

In HTML, a `<input type="file">` 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
<input type="file" />
```

In React, a `<input type="file" />` works similarly to a normal `<input/>` with some major differences. The `<input type="file" />` 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 (
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type='file' ref={input => {this.fileInput = input}} />
</label>
<br/>
<button type='submit'>Submit</button>
</form>
);
}
}
```

[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

Expand Down
26 changes: 26 additions & 0 deletions examples/components-and-props/input-type-file.js
Original file line number Diff line number Diff line change
@@ -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 (
<form onSubmit={this.handleSubmit}>
<label>
Upload file:
<input type='file' ref={input => {this.fileInput = input}} />
</label>
<br/>
<button type='submit'>Submit</button>
</form>
);
}
}

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