React props are not inherited in Custom Next.js App component - javascript

I created custom next.js App component as a class(with intention to override componentDidMount function with initializing Google analytics).
class MyApp extends App {
async componentDidMount(): Promise<void> {
await initializeAnalytics();
}
render() {
const {Component, pageProps} = this.props;
return (
<Container>
<Component {...pageProps} />
</Container>
);
}
};
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"lib": ["es5", "es2015.promise", "dom"],
"noImplicitAny": true,
"noImplicitReturns": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true,
"jsx": "react",
"baseUrl": ".",
"skipLibCheck": true,
"paths": {
"#myapp/*": ["./node_modules"]
}
}
}
The problem I'm facing is
error TS2339: Property 'props' does not exist on type MyApp.
props field should be inherited from App component that is defined as:
export default class App<P = {}, CP = {}, S = {}> extends React.Component<P & AppProps<CP>,
S> {
static origGetInitialProps: typeof appGetInitialProps;
static getInitialProps: typeof appGetInitialProps;
componentDidCatch(error: Error, _errorInfo: ErrorInfo): void;
render(): JSX.Element;
}
Why does compiler complain about missing props field on MyApp component? Shouldn't it be inherited from App component that extends React.Component?
Used versions:
Typescript 4
Next.js 10.0.0
React 17.0.0
#types/react 17.0.0

You'll need to add "esModuleInterop": true under compilerOptions in your tsconfig.json file.
I'd also suggest you use "jsx": "preserve" to avoid other React-related issues.

for you to use this.props, the props should be a method in the myApp class. therefore this.props doesnt exist as signaled by the compiler

Related

Module not found: Error: Can't resolve './App' from React 18 w/TypeScript

Getting this error when trying to upgrade to react 18.
I wonder if it has to do with my file types? I'm using typescript so I assume both the app and index have to end with a .tsx?
Teh app and index file are both within the same folder (src)
ERROR in ./src/index.tsx 12:0-24
Module not found: Error: Can't resolve './App' in 'C:\Users\CleverlyDone\Documents\GitHub\myProjectName\src'
My files are:
index.tsx
/** Vendor */
import React from "react";
/** Shared CSS */
import "./dist/css/index.css";
/** Entry Point */
import App from "./App";
/** Analytics */
// import reportWebVitals from "./reportWebVitals";
import { createRoot } from "react-dom/client";
const container = document.getElementById("app");
const root = createRoot(container!);
root.render(<App />);
App.tsx
/** Vendor **/
import React from "react";
/** CSS */
import "./dist/css/app.css";
export default function App() {
return (
<div>Placeholder</div>
);
}
Try adding this to your tsconfig.json
{
"compilerOptions": {
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"jsx": "react-jsx"
},
"include": [
"src",
]
}
Probably problem is in your webpack because you are using Typescript. In your webpack try adding ts and tsx
module.exports = {
//Rest of your code
resolve: {
extensions: ['.ts', '.tsx'],
},
};

Unable to import type from npm library

For a while now I have been using vuex-router-sync in my vue projects to keep my vuex store in sync with my routes.
For my newest project I now use Typescript for the first time.
In that context I am trying to import the State type interface from the library (which is exported according to the source code) in the following way:
import { Module } from "vuex";
import { State } from "vuex-router-sync";
interface RootState {
route: State;
}
const initialState = {};
export const processDetails: Module<any, any> = {
namespaced: true,
state: initialState,
getters: {
processId(_, _2, rootState: RootState): string {
return rootState.route.params.processId;
},
},
};
Expectation:
Above code should typecheck without error.
Actual Behaviour:
Typescript throws the following exception:
Module '"../../node_modules/vuex-router-sync/types"' has no exported member 'State'.
When I look into the file mentioned in the error it infact only contains the type declaration SyncOption which I find confusing since it seems to be exported in the same way as State in the module source code linked above.
Therefore I was wondering why State does not show up in the types file generated and if I can still import this interface somehow.
Contents of node_modules/vuex-router-sync/types/index.d.ts:
import { Store } from 'vuex';
import VueRouter from 'vue-router';
interface SyncOptions {
moduleName: string;
}
export declare function sync(
store: Store<any>,
router: VueRouter,
options?: SyncOptions
): Function;
My tsconfig.json file:
{
"compilerOptions": {
"noImplicitAny": false,
"target": "es5",
"module": "es2020",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"strictFunctionTypes": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"resolveJsonModule": true,
"baseUrl": ".",
"types": ["webpack-env", "jest"],
"paths": {
"#/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"tests/**/*.ts",
"tests/**/*.tsx"
],
"exclude": ["node_modules"]
}

React TypeScript Error : TS2322 - Type '' is not assignable to type 'IntrinsicAttributes & String'

I have a new .tsx file, and I wish pass the title to my component. However, the property "title" returns the following error with the simple code below.
Type '{ title: string; }' is not assignable to type 'IntrinsicAttributes & String'.
Property 'title' does not exist on type 'IntrinsicAttributes & String'. TS2322
import React from 'react';
import { render } from 'react-dom';
import { Nav } from "./sections";
render(
<Nav title="Suite" />,
document.getElementById('root')
);
The code for my Nav component is as follows:
import React from "react";
export const Nav = (title: String) => {
return <ul><li>{title}</li></ul>;
};
I'm troubleshooting still, and I'm wondering if the fix is related to my TSConfig somehow. Any advice would be welcomed.
In case this helps, here is a copy of my tsconfig.json
{
"compilerOptions": {
"target": "es6",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
]
}
If your Nav component is functional component then you can pass the Type to it like below:
const Nav: React.FC<React.HTMLProps<Element>> = (props => {---your component code---})

gatsbyJS: error TS2451: Cannot redeclare block-scoped variable 'react_1'

I'm trying to integrate typescript with custom routes in gatsbyjs as followed:
require("source-map-support").install();
require("ts-node").register();
exports.createPages = require("./src/createPages");
tsconfig.json
{
"include": ["./src/**/*"],
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"lib": ["es2015", "es2017"],
// "allowJs": true,
// "checkJs": true,
"jsx": "react",
"strict": false,
"esModuleInterop": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true,
"skipLibCheck": true
}
}
gastby-config.js
plugins: [
`gatsby-plugin-typescript`,
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/src/templates`,
name: "markdown-pages"
}
},
`gatsby-transformer-remark`,
`gatsby-plugin-sass`,
`gatsby-plugin-react-svg`
]
};
but when i try to import custom routes located in the routes folder i get the following error:
src/Layout.tsx(6,7): error TS2451: Cannot redeclare block-scoped variable 'react_1'.
For the routes i use
import Index from "../pages";
const routes = {
home: {
path: "/",
component: Index
}
};
// Same keys as 'routes', but the value is only the path.
const paths = Object.keys(routes).reduce((acc, route) => {
acc[route] = routes[route].path;
return acc;
}, {});
export { routes, paths };
and the createPages consists out of:
import { routes } from "./routing";
const createPages = ({ actions, graphql }) => {
const { createPage } = actions;
Object.keys(routes).forEach(route => createPage(routes[route]));
};
export default createPages;
Layout.tsx
import React from "react";
import Footer from "./Footer";
import Header from "./Header";
import "./scss/style.scss";
import "./logo.css";
const Layout: React.SFC<any> = props => {
return (
<>
<Header />
{props.children}
<Footer />
</>
);
};
export default Layout;
As i'm rather new to gatsby i've followed https://dev.to/hugecoderguy/routing-with-gatsby-and-react-4dlh to integrate the routing. but this combined with typescript seems to be giving some typescript errors. any ideas on this?
Fixed is as followed:
changed the components as followed: resolve(__dirname, "../components/pages/IndexPage.tsx")
tsconfig to:
{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": false,
"module": "commonjs",
"target": "esnext",
"jsx": "react",
"lib": ["dom", "es2015", "es2017"],
"allowSyntheticDefaultImports": true
},
"include": ["./src/**/*"]
}
Hopefully it helps someone in the future.

TypeScript dont check React props

I started migrate my React project to TypeScript and need little help. When i compile test component props checking not working.
TypeScript 2.1.4
Component.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
interface IPlayProps {
status: string,
addClass: string
}
class Play extends React.Component<IPlayProps, any> {
render() {
return (
<div>{this.props.addClass}</div>
);
}
}
ReactDOM.render(
<Play addClass={0} />,
document.getElementById('app')
);
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": false,
"allowJs": true,
"importHelpers": true,
"removeComments": true,
"jsx": "react",
"outDir": "./compiled/"
},
"include": [
"resources/scripts/player/globals.d.ts",
"resources/scripts/player/components/footer/Play.tsx"
]
}
typings.json
{
"dependencies": {
"react": "registry:npm/react#15.0.1+20160601175240",
"react-dom": "registry:npm/react-dom#15.0.1+20160826174104"
},
"globalDependencies": {
"file-saver": "registry:dt/file-saver#0.0.0+20161106021201",
"jquery": "registry:dt/jquery#1.10.0+20161119044246",
"underscore": "registry:dt/underscore#1.8.3+20161123125004",
"x2js": "registry:dt/x2js#0.0.0+20160510002910"
}
}
globals.d.ts
/// <reference path="../../../typings/main.d.ts" />
/// <reference path="../../../typings/index.d.ts" />
Render component with wrong prop type
<Play addClass={0} />
and no errors in terminal, why?

Categories

Resources