Skip to content
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

Fixed file input value when used on forms #1362

Merged
merged 2 commits into from Nov 4, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions lib/src/file-input/FileInput.test.js
Expand Up @@ -281,4 +281,31 @@ describe("FileInput component tests", () => {
]);
});
});

test("File input sends value when submitted in a form", () => {
const newFile = new File(["newFile"], "newFile.pdf", { type: "pdf" });
const handlerOnSubmit = jest.fn((e) => {
e.preventDefault();
const formData = new FormData(e.target);
const formProps = Object.fromEntries(formData);
expect(formProps).toStrictEqual({ file: newFile });
});
const { getByText, getByLabelText } = render(
<form onSubmit={handlerOnSubmit}>
<DxcFileInput
label="File input label"
name="file"
helperText="File input helper text"
mode="filedrop"
buttonLabel="Choose"
dropAreaLabel="(or drop the files)"
/>
<button type="submit">Submit</button>
</form>
);
const inputFile = getByLabelText("File input label", { hidden: true });
const submit = getByText("Submit");
fireEvent.change(inputFile, { target: { files: [newFile] } });
userEvent.click(submit);
});
});
31 changes: 24 additions & 7 deletions lib/src/file-input/FileInput.tsx
Expand Up @@ -186,7 +186,17 @@ const DxcFileInput = ({
<HelperText disabled={disabled}>{helperText}</HelperText>
{mode === "file" ? (
<FileContainer multiple={multiple} files={files}>
<HiddenInputFile id={fileInputId} type="file" accept={accept} multiple={multiple} onChange={selectFiles} />
<ValueInput
id={fileInputId}
type="file"
accept={accept}
multiple={multiple}
onChange={selectFiles}
name={name}
disabled={disabled}
readOnly
aria-hidden="true"
/>
<DxcButton
mode="secondary"
label={
Expand Down Expand Up @@ -223,7 +233,17 @@ const DxcFileInput = ({
</FileContainer>
) : (
<Container>
<HiddenInputFile id={fileInputId} type="file" accept={accept} multiple={multiple} onChange={selectFiles} />
<ValueInput
id={fileInputId}
type="file"
accept={accept}
multiple={multiple}
onChange={selectFiles}
name={name}
disabled={disabled}
readOnly
aria-hidden="true"
/>
<DragDropArea
isDragging={isDragging}
disabled={disabled}
Expand Down Expand Up @@ -351,11 +371,8 @@ const FileContainer = styled.div`
margin-top: 0.25rem;
`;

const HiddenInputFile = styled.input`
visibility: hidden;
position: absolute;
width: 0px;
height: 0px;
const ValueInput = styled.input`
display: none;
`;

const ButtonContainer = styled.div`
Expand Down