Skip to content

Instantly share code, notes, and snippets.

@jamesporter
Created July 8, 2018 09:16
Show Gist options
  • Save jamesporter/58954a1026f0eee1caa2989c22550da1 to your computer and use it in GitHub Desktop.
Save jamesporter/58954a1026f0eee1caa2989c22550da1 to your computer and use it in GitHub Desktop.
Quick React component (in TypeScript) to open a file/read as text/return contents via callback
import * as React from "react";
type OpenFileButtonProps = {
label: string;
onOpen: (file: string) => void;
};
export default class OpenFileButton extends React.Component<
OpenFileButtonProps
> {
private input: any;
render() {
return (
<a onClick={this.onClick} className="little-button">
{this.props.label}
<input
type="file"
id="file"
accept=".json"
ref={comp => (this.input = comp)}
style={{ display: "none" }}
onChange={this.fileChanged}
/>
</a>
);
}
private onClick = () => {
this.input.click();
};
private fileChanged = (evt: any) => {
const file = this.input.files[0];
if (!file) {
console.error("no file");
return;
}
const fr = new FileReader();
fr.onload = e => {
if (e && e.target) {
const content = e.target.result;
if (content) {
this.props.onOpen(content);
} else {
console.error("Unable to read content");
}
} else {
console.error(
"No event/target supplied for onload callback to readAsText"
);
}
};
fr.readAsText(file);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment