How to Export an Image From a React Redux App
You can find the working example for this lesson in the
code/04-redux/04.17-exporting-an-image
folder.
Let's allow exporting the picture to a file. To do this we'll need to retrieve the bitmap information from our canvas, transform it into a Blob and then save it as a file locally.
The file saving logic will be defined in a separate component. We will use the React Context API to make the canvas reference available there.
Let's define the CanvasProvider
. Create a new file src/CanvasContext.tsx
with the following contents:
xxxxxxxxxx
import React, {
createContext,
PropsWithChildren,
useRef,
RefObject,
useContext
} from "react"
​
export const CanvasContext = createContext<
RefObject<HTMLCanvasElement>
>({} as RefObject<HTMLCanvasElement>)
​
export const CanvasProvider = ({
children
}: PropsWithChildren<{}>) => {
const canvasRef = useRef<HTMLCanvasElement>(null)
​
return (
<CanvasContext.Provider value={canvasRef}>
{children}
</CanvasContext.Provider>
)
}
​
export const useCanvas = () => useContext(CanvasContext)
This provider will store the reference to the context. Go to src/index.tsx
and wrap the component tree into the CanvasContext
:
xxxxxxxxxx
import { CanvasProvider } from "./CanvasContext"
// ...
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<CanvasProvider>
<App />
</CanvasProvider>
</Provider>
</React.StrictMode>,
document.getElementById("root")
)
Go to src/App.tsx
, remove the useRef
import and import the useCanvas
hook:
xxxxxxxxxx
import React, { useEffect } from "react"
// ...
import { useCanvas } from "./CanvasContext"
Change the useRef
call to useCanvas
:
xxxxxxxxxx
const canvasRef = useCanvas()
Define the getCanvasImage
#
Go to src/utils/canvasUtils.ts
and add the getCanvasImage
function:
xxxxxxxxxx
export const getCanvasImage = (
canvas: HTMLCanvasElement | null
): Promise<null | Blob> => {
return new Promise((resolve, reject) => {
if (!canvas) {
return reject(null)
}
canvas.toBlob(resolve)
})
}
This lesson preview is part of the Fullstack React with TypeScript Masterclass course and can be unlocked immediately with a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack React with TypeScript Masterclass with a single-time purchase.
