A simple way to use FileReader in Reactjs component
To get the content of the file reader in react I used the callback function to update the state as used in the MDN Web docs.
React component
// state to store the base64
const [base64File, setbase64File] = useState(null);
// Create the callback function
const base64Callback = async (err, res) => {
if (!err) {
setbase64File(res); // setting the state is the important part
} else {
setbase64File(null);
}
};
// call function to convert to base64
getBase64(fileObj, base64Callback);
Function to convert to base64
async function getBase64(file, callback) {
const reader = new FileReader();
reader.onload = () => callback(null, reader.result);
reader.onerror = (error) => callback(error);
reader.readAsDataURL(file);
}
export default getBase64;
The above code is a modified version of code from the MDN Web docs site click for more