Using Astro.js with Preact and React hook forms - javascript

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>
);
};

Related

Vite builds React app incorrectly (infinitely duplicates html document inside <object /> element)

I've just built a simple enough app in react using npm create vite#latest --template react-ts
Didn't touch any config files. Everything was fine while i was working in dev mod.
But when i tried to build and preview the app (docs say it's production mode for a vite app of something like this), i've got multiple problems:
The app loads very(!) slow (about 7 seconds). Guess it's due to infinite loop of documents.
<object /> elements seem to contain another html document inside themself (one <object /> element even contains a full duplicate of the core html document, what causes recursion).
Here's how it looks in dev mode
And here's what happens in preview
And how it looks
NOTE: there are not any errors or warnings in any logs (neither server, nor client)
I've realized it's some unexpected behavior of <object /> element, but i can't find why vite does this.
I tried to rewrite my <object /> into <object></object>. but it didn't help.
Here are some parts of my codebase connected to the issue:
A component with the problem:
import '../styles/header.scss';
export default function Header() {
return (
<header>
<div className="logo">
<object
data="./src/assets/ic_logo.svg"
type="image/svg+xml"
className="headerLogo"
/>
<span>Wrench CRM</span>
</div>
<div className="rightSide">
<object
data="./src/assets/ic_person.svg"
type="image/svg+xml"
className="headerPersonIcon"
/>
<span>Имя Фамилия</span>
</div>
</header>
);
}
How multiple components connect:
import Header from '../components/header';
import Menu from '../components/menu';
import SearchContent from '../components/searchContent';
function App() {
return (
<>
<Header />
<div className="content">
<Menu />
<SearchContent />
</div>
</>
);
}
export default App;
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
vite.config.ts
import { defineConfig } from 'vite';
import react from '#vitejs/plugin-react';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
});
package.json
{
"name": "x-lab",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"#types/node": "^18.11.5",
"#types/react": "^18.0.17",
"#types/react-dom": "^18.0.6",
"#vitejs/plugin-react": "^2.1.0",
"sass": "^1.55.0",
"typescript": "^4.6.4",
"vite": "^3.1.0"
}
}

Component "font-awesome-icon" has already been registered in target app (NuxtJS 3)

I'm using NuxtJS 3 with FontAwesome. I've managed to get it working, but I receive a warning the console of my IDE which says:
[Vue warn]: Component "font-awesome-icon" has already been registered in target app.
Where does it come from? Is this a problem? And how to fix this?
Here is my package.json:
{
"private": true,
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview"
},
"devDependencies": {
"#nuxtjs/google-fonts": "^3.0.0-0",
"nuxt": "3.0.0-rc.6",
"sass": "^1.54.0",
"sass-loader": "^13.0.2"
},
"dependencies": {
"#fortawesome/fontawesome-svg-core": "^6.1.2",
"#fortawesome/free-brands-svg-icons": "^6.1.2",
"#fortawesome/free-regular-svg-icons": "^6.1.2",
"#fortawesome/free-solid-svg-icons": "^6.1.2",
"#fortawesome/vue-fontawesome": "^3.0.1",
"#nuxtjs/fontawesome": "^1.1.2",
"firebase": "^9.9.1"
}
}
My nuxt.config.ts:
import { defineNuxtConfig } from 'nuxt'
export default defineNuxtConfig({
plugins: [
'~/plugins/fontawesome.ts',
'~/plugins/firebase.client.ts'
],
buildModules: [
'#nuxtjs/google-fonts'
],
googleFonts: {
display: 'swap',
prefetch: true,
preconnect: true,
preload: true,
families: {
Nunito: true,
}
},
css: [
'#fortawesome/fontawesome-svg-core/styles.css',
],
runtimeConfig: {
FIREBASE_API_KEY: process.env.FIREBASE_API_KEY,
},
})
And the fontawesome plugin in ~/plugins/fontawesome.ts:
import { library, config } from '#fortawesome/fontawesome-svg-core'
import { FontAwesomeIcon } from '#fortawesome/vue-fontawesome'
import { fas } from '#fortawesome/free-solid-svg-icons'
import { far } from '#fortawesome/free-regular-svg-icons'
import { fab } from '#fortawesome/free-brands-svg-icons'
import { defineNuxtPlugin } from "nuxt/app";
config.autoAddCss = false
library.add(fas)
library.add(fab)
library.add(far)
export default defineNuxtPlugin((nuxtApp) => {
// This line creates problems with TypeScript whereas it is not raising any runtime error
// #ts-ignore
nuxtApp.vueApp.component('font-awesome-icon', FontAwesomeIcon, {});
});
Several problems:
TypeScript doesn't like calling nuxtApp.vueApp.component() like this because apparently there is no such function declared for 3 arguments given by the FontAwesome documentation
The warning is annoying and I don't find anything that could help me.
My icons do show up (so it looks like this is working despite the warning).
Did I do something wrong?

Next.js Error: Element type is invalid: expected a string - while trying to use Next.js with MUI

I'm trying to use Next.js with MUI v5 and in order to do so I had to make some configurations to remove server-side injected CSS and fix the resolution order. I used this tutorial and followed every step. but when I run the script yarn dev or npm run dev I face this error:
What should I do to fix this problem?
Here's my _document.js file:
import * as React from 'react'
import Document, { Html, Head, Main, NextScript } from 'next/document'
import createEmotionServer from '#emotion/server/create-instance'
import createEmotionCache from '../src/utility/createEmotionCache'
export default class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
MyDocument.getInitialProps = async (ctx) => {
const originalRenderPage = ctx.renderPage
const cache = createEmotionCache()
const { extractCriticalToChunks } = createEmotionServer(cache)
/* eslint-disable */
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) =>
function EnhanceApp(props) {
return <App emotionCache={cache} {...props} />
},
})
/* eslint-enable */
const initialProps = await Document.getInitialProps(ctx)
const emotionStyles = extractCriticalToChunks(initialProps.html)
const emotionStyleTags = emotionStyles.styles.map((style) => (
<style
data-emotion={`${style.key} ${style.ids.join(' ')}`}
key={style.key}
dangerouslySetInnerHTML={{ __html: style.css }}
/>
))
return {
...initialProps,
styles: [
...React.Children.toArray(initialProps.styles),
...emotionStyleTags,
],
}
}
And here's my package.json file:
{
"name": "testing-next-app",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"#emotion/cache": "^11.7.1",
"#emotion/react": "^11.7.1",
"#emotion/server": "^11.4.0",
"#emotion/styled": "^11.6.0",
"#fontsource/roboto": "^4.5.2",
"#mui/icons-material": "^5.3.1",
"#mui/material": "^5.4.0",
"next": "12.0.10",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "8.8.0",
"eslint-config-next": "12.0.10",
"prop-types": "^15.8.1"
}
}

SyntaxError: Cannot use import statement outside a module when testing using jest and react-testing-library

I am always getting this error whenever trying to test my file using jest and react-testing-library
error --
Details:
/Users/user/dev/system-wheels/src/Constants/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { MAP_API_KEY } from "../config.local";
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-cli/node_modules/jest-runtime/build/index.js:1517:14)
at Object.<anonymous> (node_modules/graceful-fs/polyfills.js:1:99)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.777 s
Ran all test suites matching /Loginpage.test.js/i.
error Command failed with exit code 1.
Here is my package.json-
{
"name": "system-wheels",
"version": "0.1.0",
"private": true,
"dependencies": {
"#firebase/app": "^0.6.29",
"#firebase/messaging": "^0.7.15",
"#testing-library/jest-dom": "^5.14.1",
"#testing-library/react": "^12.0.0",
"#testing-library/user-event": "^13.2.1",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-places-autocomplete": "^7.3.0",
"react-redux": "^7.2.2",
"react-router": "^5.2.0",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",
"react-window": "^1.8.6",
"redux": "^4.0.5",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0",
"reselect": "^4.0.0",
"storage": "file:./src/Packages/Storage/",
"styled-components": "^5.2.1",
"web-vitals": "^1.0.1"
},
"scripts": {
"start": "bash ./scripts/init.sh && react-scripts start",
"build": "bash ./scripts/init.sh && react-scripts build",
"test": "bash ./scripts/init.sh && react-scripts test --transformIgnorePatterns \"node_modules/(?!#toolz/allow-react)/\" --env=jsdom",
"test2": " jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"alias": {
"modules": "src/Modules/",
"components": "src/Common/Components/",
"hooks": "src/Hooks/",
"helper": "src/Helper/",
"common": "src/Common/",
"globalStyles": "src/GlobalStyles/",
"constants": "src/Constants/",
"assets": "src/Assets/",
"context": "src/Context/",
"route": "src/Routes/"
},
"devDependencies": {
"#babel/plugin-transform-modules-commonjs": "^7.15.0",
"#babel/plugin-transform-runtime": "^7.15.0",
"#babel/preset-env": "^7.15.0",
"#babel/preset-react": "^7.14.5",
"#babel/runtime": "^7.15.3",
"babel-jest": "^27.1.0",
"jest": "^27.1.0",
"ts-jest": "^27.0.5"
}
}
Here is my - babel.config.js
module.exports = {
presets: [
["#babel/preset-env", { targets: { node: "current" } }],
"#babel/preset-react",
],
};
Here is my - jest.config.js
module.exports = {
preset: "ts-jest",
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.(ts|tsx)?$": "ts-jest",
"^.+\\.(js|jsx)?$": "babel-jest",
},
moduleNameMapper: {
"^constants$": "<rootDir>/src/Constants/",
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js",
"^modules(.*)$": "<rootDir>/src/Modules/",
"^helper$": "<rootDir>/src/helper/",
"^context$": "<rootDir>/src/Context/",
"^route(.*)$": "<rootDir>/src/Routes/",
"^assets(.*)$": "<rootDir>/src/Assets/",
"^globalStyles(.*)$": "<rootDir>/src/GlobalStyles/",
"^common(.*)$": "<rootDir>/src/Common/",
"^hooks(.*)$": "<rootDir>/src/Hooks/",
"^components(.*)$": "<rootDir>/src/Common/Components/",
},
};
Here is the unit test
import "#testing-library/jest-dom";
import React from "react";
import { render, fireEvent, waitFor, screen } from "#testing-library/react";
import LoginPage from "../Views/LoginPage";
describe("Login page testing", () => {
let wrapper;
beforeEach(() => {
wrapper = render(<LoginPage />);
});
test("should contain input fields", () => {
screen.getByLabelText("Your Email");
screen.getByLabelText("Password");
});
});
Here is the LoginPage component
import React, { useState, useCallback } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import Form from "./Form";
import { loginUser, updateLoginType } from "../../../Common/ActionCreators";
import useAlert from "../../../Hooks/useAlert";
import Path from "../../../Routes/Path";
import BACK_IMAGE from "../assets/background.png";
import SOFTWARE_IMAGE from "assets/OMS.svg";
import { ViewPortContainer, BackgroundImage, SoftwareLogo } from "../styles";
const { companySelection } = Path.authorized;
const LoginPage = ({ loginUser, history, updateLoginType }) => {
const [inProgress, updateProgress] = useState(false);
const { showAlert } = useAlert();
const navigateToCompanySelectionPage = () => {
history.replace(companySelection.view.path);
};
const onFormSubmit = useCallback(async (values, resetForm) => {
const { login_email, login_password, login_loginAs } = values;
try {
updateProgress(true);
updateLoginType({ isLoggedInAsAdmin: Boolean(login_loginAs) });
await loginUser({
emailOrMobile: login_email.toLowerCase(),
password: login_password,
isAdmin: Boolean(login_loginAs),
});
updateProgress(false);
navigateToCompanySelectionPage();
} catch (err) {
updateProgress(false);
showAlert({ message: err[0], type: "error" });
}
}, []);
return (
<ViewPortContainer>
<SoftwareLogo src={SOFTWARE_IMAGE} />
<BackgroundImage src={BACK_IMAGE} />
<Form onFormSubmit={onFormSubmit} inProgress={inProgress} />
</ViewPortContainer>
);
};
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
loginUser,
updateLoginType,
},
dispatch
);
export default connect(null, mapDispatchToProps)(LoginPage);
I am stuck at this problem for days, please Help

importing any component from react-bootstrap throws error

I have some weird error everytime when I'm trying to use some component from 'react-bootstrap'. Here is some small example where I'm importing "HelpBlock" component.
import PropTypes from 'prop-types';
import React from 'react';
import HelpBlock from 'react-bootstrap';
class RegisterFormDetails extends React.Component {
...
<HelpBlock>{validationErrorMessage}</HelpBlock>
}
</div>
</div>
);
};
export default RegisterFormDetails;
but then I'm getting this error
Attempted import error: 'react-bootstrap' does not contain a default export (imported as 'HelpBlock').
my package.json
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
],
"devDependencies": {
"bootstrap": "^4.3.1",
"lodash": "^4.17.11",
"prop-types": "^15.7.2",
"react": "^16.8.3",
"react-bootstrap": "^0.32.1",
"react-bootstrap-sweetalert": "^4.4.1",
"react-dom": "^16.8.3",
"react-scripts": "^2.1.5",
"react-select": "^2.4.1"
}
}
somebody can help me ? I have rechecked the react-bootstrap folder in node_modules and contains the component which I'm trying to import
You can import individual components like:
import HelpBlock from 'react-bootstrap/HelpBlock ';
The first one is importing component directly, The above is a default import. Default imports are exported with export default .... There can be only a single default export. Since 'react-bootstrap' does not contain a default export , you have to import directly.
or import { HelpBlock } from 'react-bootstrap';
Here, only HelpBlock will be imported. Hope it helps.
This article will help you to understand es6 modules.

Categories

Resources