This content originally appeared on DEV Community and was authored by es404020
As easy as file upload my sound to mid level or senior developer, junior developer still struggle to implement file upload without having to use the default input tag for file upload .In this tutorial we would learn how to implement file upload on a button click with next.js and Chakara UI.
Step 1:
<input type="file"
ref={hiddenFileInput}
onChange={handleChange}
accept="image/*"
style={{ display: 'none' }} />
<IconButton onClick={handleClick} size="xx-small" pos="absolute" zIndex="10" left="5px" bottom="5px"
aria-label="file upload " icon={<BiCloudUpload />} />
Step 2:
We have to create an input filed with a style display to none. This helps us hide the input tag.
const hiddenFileInput = useRef(null);
const handleChange = event => {
if (event.target.files && event.target.files[0]) {
const i = event.target.files[0];
const body = new FormData();
body.append("image", i);
}
};
const handleClick = event => {
hiddenFileInput.current.click();
};
Using the react useRef hook as a reference on the input tag we can access the content of tag .
Calling the handleClick helps call a click event on the invisible input tag giving us the chances to pick a file for upload.
The handleChange help to listern to change on the input tag. When handling file upload it is important to use FormData() if you intend to store on a server.
Thanks for reading .
This content originally appeared on DEV Community and was authored by es404020
es404020 | Sciencx (2021-11-04T07:49:33+00:00) File Upload in Next js. Retrieved from https://www.scien.cx/2021/11/04/file-upload-in-next-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.