Commit f36d86c4 authored by Nicolas Frandeboeuf's avatar Nicolas Frandeboeuf Committed by Antoine
Browse files

Migrate FileInput to Typescript

parent 7cd463b6
Pipeline #375100 passed with stage
in 4 minutes and 24 seconds
import React from 'react';
import PropTypes from 'prop-types';
import { translate as $t } from '../../helpers';
class FileInput extends React.Component {
state = {
fileLabel: $t('client.general.no_file_selected'),
};
refInput = React.createRef();
handleChange = event => {
const selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.onload = () => {
this.props.onChange(fileReader.result);
};
fileReader.readAsText(selectedFile);
this.setState({ fileLabel: selectedFile.name });
};
clear() {
this.refInput.current.value = null;
this.setState({ fileLabel: $t('client.general.no_file_selected') });
}
render() {
return (
<span className="file-input">
<label className="btn">
{$t('client.general.browse')}
<input ref={this.refInput} type="file" onChange={this.handleChange} />
</label>
<output>{this.state.fileLabel}</output>
</span>
);
}
}
FileInput.propTypes = {
// Callback receiving the validated text input.
onChange: PropTypes.func.isRequired,
};
export default FileInput;
import React, {
forwardRef,
useCallback,
useRef,
useState,
useImperativeHandle,
ChangeEvent,
} from 'react';
import { translate as $t } from '../../helpers';
interface FileInputProps {
// Callback receiving file input.
onChange: (result: string | ArrayBuffer | null) => void;
}
interface FileInputExposedMethods {
clear: () => void;
}
const FileInput = forwardRef<FileInputExposedMethods, FileInputProps>((props, ref) => {
const [fileLabel, setFileLabel] = useState($t('client.general.no_file_selected'));
const internalRef = useRef<HTMLInputElement>(null);
useImperativeHandle(ref, () => ({
clear() {
if (internalRef.current) {
internalRef.current.value = '';
}
setFileLabel($t('client.general.no_file_selected'));
},
}));
const { onChange: onChangeProps } = props;
const onChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
const selectedFile = (event.currentTarget.files as FileList)[0];
const fileReader = new FileReader();
fileReader.onload = () => {
onChangeProps(fileReader.result);
};
fileReader.readAsText(selectedFile);
setFileLabel(selectedFile.name);
},
[onChangeProps]
);
return (
<span className="file-input">
<label className="btn">
{$t('client.general.browse')}
<input ref={internalRef} type="file" onChange={onChange} />
</label>
<output>{fileLabel}</output>
</span>
);
});
export default FileInput;
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment