Skip to main content

React Hook Form

Here an example if you want to plug MuiColorInput to your form using React Hook Form.

import React from "react";
import ReactDOM from "react-dom";
import Button from "@mui/material/Button";
import { MuiColorInput, matchIsValidColor } from "@sherifmagdy/mui-color-input";
import { Controller, useForm } from "react-hook-form";

const App = () => {
const { control, handleSubmit } = useForm({
defaultValues: {
color: "#ffffff"
}
});

const onSubmit = (data) => {
alert(JSON.stringify(data));
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="color"
control={control}
rules={{ validate: matchIsValidColor }}
render={({ field, fieldState }) => (
<MuiColorInput
value={field.value}
onChange={(newValue) => field.onChange(newValue)}
format="hex"
slotProps={{
textField: {
name: field.name,
onBlur: field.onBlur,
helperText: fieldState.invalid ? "Color is invalid" : "",
error: fieldState.invalid
}
}}
/>
)}
/>
<div>
<Button type="submit" variant="contained" sx={{ mt: 2 }}>
Submit
</Button>
</div>
</form>
)
}

Note: In v10, the component ref targets the root <span> rather than the input, so React Hook Form's automatic focus-on-error is not wired by default. The field.ref is intentionally omitted from the example above — manage focus explicitly if your form relies on it.

Edit on CodeSandbox