i am new to programming and learning on the go. what i am trying to do currently is to create a form field like below that uploads a file on clicking a button.
and once file uploaded and before submitting the file to api should see the file name in form field like below
i have tried like below but that shows only browse file button but doesnt sow the input field with Add file placeholder.
<input
type="file"
id={`${fieldRoot}.file`}
ref={fileInput}
style={{ display: 'none' }}
accept=".pem"
onChange={() => {
/*do something*/
console.log('hello')
}}
/>
<Button
minWidth="126px"
//onClick={handleUploadClick}
>
Browse file
</Button>
Could someone help me with this. thanks.
<input type="file"/> also is a input. So you can use <label> tag and style it look like a button. In this case, I use image instead.
I'm using hidden attribute to make the actual <input /> invisible.
<input
type="file"
id="avatar"
onChange={fileSelectedHandler}
hidden
/>
<label className={profileStyle.uploadLabel} htmlFor="avatar">
<Image
width="25px"
height="25px"
src="/icons/upload-image-icon.jpeg"
alt="upload-avatar"
/>
</label>
Here is what you want:
import React, { useState } from "react";
export const Upload = () => {
const [filename, setFilename] = useState("");
return (
<>
<input
value={filename}
type="text"
style={{
width: 200,
height: 28,
padding: 0,
border: "1px solid #767676"
}}
/>
<input
type="file"
id="upload"
hidden
onChange={(e) => {
// You have your file detail in e.tartget.files
console.log(e.target.files[0]);
setFilename(e.target.files[0].name);
}}
/>
<label
htmlFor="upload"
style={{
width: 90,
background: "#767676",
color: "#fff",
padding: 5
}}
>
Browse
</label>
</>
);
};
Check this Demo