How to add react signature canvas on react hook form
2 min readMay 31, 2021
Hello, In the previous article, I told you about the yup validations with the react hook form. Before reading this article please read below.
Today I want to show, how to use react-signature-canvas with react-hook-form
yarn add react-signature-canvas
App.js
import SignaturePad from “react-signature-canvas”;
import { useRef } from "react";
import { useForm, Controller } from "react-hook-form";
We load requirements that are not in the other article and also updating the form schema.
const formSchema = yup.object().shape({
email: yup.string().email().required(),
password: yup.string().min(6).required(),
imageUrl: yup.string().required()
.matches(/^data:image\/(?:gif|png|jpeg|bmp|webp|svg\+xml)(?:;charset=utf-8)?;base64,(?:[A-Za-z0-9]|[+/])+={0,2}/,
"Signature must be png"
),
});
let sigCanvas = useRef({});
const {
register,
handleSubmit,
control,
formState: { errors } = {},
} = useForm({
mode: "onBlur",
resolver: yupResolver(formSchema),
});
const formatIntoPng = () => {
if (sigCanvas.current) {
const dataURL = sigCanvas.current.toDataURL();
return dataURL;
}
};
<FormControl
isInvalid={!!errors?.imageUrl?.message}
errortext={errors?.imageUrl?.message}
p="4"
isRequired
>
<FormLabel>Signature</FormLabel>
<Controller
name="imageUrl"
control={control}
render={({ field }) => (
<SignaturePad
ref={sigCanvas}
onEnd={() => field.onChange(formatIntoPng())}
penColor="green"
canvasProps={{
width: 315,
height: 200,
style: { border: "1px solid green" },
}}
/>
)}
/>
<FormErrorMessage>{errors?.imageUrl?.message}</FormErrorMessage>
</FormControl>
Don’t forget to adjust the ‘chakra’ settings from the other article.
You can reach all codes here.