2

I have a problem with setting up Preact to work with library https://react-hook-form.com

When i try to use it i get Cannot read properties of undefined (reading 'useForm')

Is it even possible to use this library with Preact and Astro

Here is my tsconfig.json

{
  "extends": "astro/tsconfigs/base",
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "preact",
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": false,
    "baseUrl": ".",
    "paths": {
      "react": ["./node_modules/preact/compat/"],
      "react-dom": ["./node_modules/preact/compat/"],
      "@styles/*": ["./src/styles/*"],
      "@components/*": ["./src/components/*"],
      "@layouts/*": ["./src/layouts/*"]
    }
  }
}

here is package.json

{
  "name": "portfolio",
  "type": "module",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "dev": "astro dev",
    "start": "astro dev",
    "build": "astro build",
    "preview": "astro preview",
    "astro": "astro"
  },
  "dependencies": {
    "@astrojs/preact": "^2.0.0",
    "@fontsource/lato": "^4.5.10",
    "astro": "^2.0.0",
    "astro-icon": "^0.8.0",
    "astro-imagetools": "^0.7.6",
    "preact": "^10.6.5",
    "react-hook-form": "^7.42.1"
  },
  "overrides": {
    "react": "npm:@preact/compat@latest",
    "react-dom": "npm:@preact/compat@latest"
  }
}

and the astro.config.mjs

import { defineConfig } from "astro/config";

// https://astro.build/config
import preact from "@astrojs/preact";

import { astroImageTools } from "astro-imagetools";

// https://astro.build/config
export default defineConfig({
  integrations: [preact({ compat: true }), astroImageTools],
});

Edit add how i use it

import style from "@styles/form.module.css";
import { h, FunctionComponent } from "preact";
import { useForm } from "react-hook-form";

import { Input } from "./Input";
import { Textarea } from "./Textarea";

// Todo: figure out how to integrate React hook form with Astro.js and Preact

export const Form = () => {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors },
  } = useForm();
  const onSubmit = (data) => console.log(data);
  return (
    <form onSubmit={onSubmit}>
      <div class={style.title}>
        <Input type="text" text="Email title" name="emailTitle" />
      </div>
      <div class={style.email}>
        <Input type="email" text="Email adress" name="emailAdress" />
      </div>
      <div class={style.message}>
        <Textarea text="Message" name="message" />
      </div>
      <div class={style.send_button}>
        <button>Send message</button>
      </div>
    </form>
  );
};
IvonaK
  • 119
  • 10

0 Answers0