Hi I have designed a file upload button by using HTML CSS and JS, I need the same design in React so I need to know how we do the same thing in React?
HTML Code:
<br>
<!-- actual upload which is hidden -->
<input type="file" id="actual-btn" hidden/>
<!-- our custom upload button -->
<label for="actual-btn">Choose File</label>
<!-- name of file chosen -->
<span id="file-chosen">No file chosen</span>
CSS Code :
label {
background-color: white;
color: black;
content:"gdg";
padding: 0.5rem;
font-family: sans-serif;
border: 2px solid black;
border-radius: 0.3rem;
cursor: pointer;
margin-top: 1rem;
padding: 10px 55px;
}
#file-chosen{
margin-left: 0.3rem;
font-family: sans-serif;
}
Javscript code :
const actualBtn = document.getElementById('actual-btn');
const fileChosen = document.getElementById('file-chosen');
actualBtn.addEventListener('change', function(){
fileChosen.textContent = this.files[0].name
})
Link : https://codepen.io/anishkuls/pen/VwXVJoM
CodePudding user response:
In Upload.js
:
import { useRef, useState } from "react";
const Upload = () => {
const actualBtnRef = useRef(null);
const [fileName, setFileName] = useState("No file chosen");
return (
<>
<input type="file" id="actual-btn" hidden ref={actualBtnRef} onChange={() => setFileName(actualBtnRef.current.files[0].name)} />
<label htmlFor="actual-btn">Choose File</label>
<span id="file-chosen">{fileName}</span>
</>
);
};
export default Upload;