Tag Archives: react.js

[Solved] React Error: ReactDOM.render is no longer supported in React 18.

Error message:

ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it’s running React

 

ReactDOM.React 18 no longer supports rendering. Use createRoot instead. Before you switch to the new API, your application will behave as if it is running React 17

Reason:
React team has launched the latest version of 18.0, in which React 18 no longer supports ReactDOM.render

Console error:

Solution:
Use createRoot in the index.js file

import React from 'react'
import ReactDOM from 'react-dom'
import TopList from './TopList'

// Use createRoot
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root')
const root = createRoot(container)
root.render(<TopList/>)

// report error
// ReactDOM.render( < TopList /> , document.getElementById('root'))

 

[Solved] React Invariant Violation: Minified React error #130

React Invariant Violation: Minified React error #130

The local operation of react is OK. After being packaged, an error is reported as follows:

When you encounter such a problem, usually there is a problem with import, either the name is written wrong, or case, or the imported component does not exist can not be found! Check the import of the problem area carefully and you will usually find the reason.

I encountered the reason is: in the same ts file exported more than one, and then imported elsewhere, the local operation are normal no problem, but after packaging may be due to sub-packaging or what, resulting in other places import place can not be found.

Solution: I wrote a separate file for the exported component, and after the other import references were modified, it was all good.

[Solved] React Dependency Error: Invalid tag name “^np.0.2“ of package “react@^np.0.2“: Tags may not have an

When writing the carousel diagram, you need to install dependencies. Execute the following command. When you execute, you report an error, saying that it is a version problem. After you reduce the version of react, you search the Internet. Later, when you execute NPM install, you report various dependency errors

  npm install --save react-swipeable-views
    npm install --save react-swipeable-views-utils

The following is the error message: read the error message and say it is a problem with the version of the files in node_modules, but there is still an error after trying to change them. I can only ask you for advice.

the following is the package.json file

{
  "name": "react-goodlive-home",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@babel/core": "^7.16.0",
    "@pmmmwh/react-refresh-webpack-plugin": "^0.5.3",
    "@svgr/webpack": "^6.3.1",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^0.27.2",
    "babel-jest": "^27.4.2",
    "babel-loader": "^8.2.3",
    "babel-plugin-named-asset-import": "^0.3.8",
    "babel-preset-react-app": "^10.0.1",
    "bfj": "^7.0.2",
    "browserslist": "^4.18.1",
    "camelcase": "^6.2.1",
    "case-sensitive-paths-webpack-plugin": "^2.4.0",
    "css-loader": "^6.5.1",
    "css-minimizer-webpack-plugin": "^3.2.0",
    "dotenv": "^10.0.0",
    "dotenv-expand": "^5.1.0",
    "eslint": "^8.3.0",
    "eslint-config-react-app": "^7.0.1",
    "eslint-webpack-plugin": "^3.1.1",
    "file-loader": "^6.2.0",
    "fs-extra": "^10.0.0",
    "html-webpack-plugin": "^5.5.0",
    "identity-obj-proxy": "^3.0.0",
    "jest": "^27.4.3",
    "jest-resolve": "^27.4.2",
    "jest-watch-typeahead": "^1.0.0",
    "mini-css-extract-plugin": "^2.4.5",
    "postcss": "^8.4.4",
    "postcss-flexbugs-fixes": "^5.0.2",
    "postcss-loader": "^6.2.1",
    "postcss-normalize": "^10.0.1",
    "postcss-preset-env": "^7.0.1",
    "prompts": "^2.4.2",
    "react": "^17.0.2",
    "react-app-polyfill": "^3.0.0",
    "react-dev-utils": "^12.0.1",
    "react-dom": "^17.0.2",
    "react-refresh": "^0.11.0",
    "react-router-dom": "^6.3.0",
    "resolve": "^1.20.0",
    "resolve-url-loader": "^4.0.0",
    "sass-loader": "^12.3.0",
    "semver": "^7.3.5",
    "source-map-loader": "^3.0.0",
    "style-loader": "^3.3.1",
    "tailwindcss": "^3.0.2",
    "terser-webpack-plugin": "^5.2.5",
    "web-vitals": "^2.1.4",
    "webpack": "^5.64.4",
    "webpack-dev-server": "^4.6.0",
    "webpack-manifest-plugin": "^4.0.2",
    "workbox-webpack-plugin": "^6.4.1"
  },
  "scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  },
  "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"
    ]
  },
  "jest": {
    "roots": [
      "<rootDir>/src"
    ],
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}",
      "!src/**/*.d.ts"
    ],
    "setupFiles": [
      "react-app-polyfill/jsdom"
    ],
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    "testMatch": [
      "<rootDir>/src/**/__tests__/**/*.{js,jsx,ts,tsx}",
      "<rootDir>/src/**/*.{spec,test}.{js,jsx,ts,tsx}"
    ],
    "testEnvironment": "jsdom",
    "transform": {
      "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "<rootDir>/config/jest/babelTransform.js",
      "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
      "^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
    },
    "transformIgnorePatterns": [
      "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$",
      "^.+\\.module\\.(css|sass|scss)$"
    ],
    "modulePaths": [],
    "moduleNameMapper": {
      "^react-native$": "react-native-web",
      "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
    },
    "moduleFileExtensions": [
      "web.js",
      "js",
      "web.ts",
      "ts",
      "web.tsx",
      "tsx",
      "json",
      "web.jsx",
      "jsx",
      "node"
    ],
    "watchPlugins": [
      "jest-watch-typeahead/filename",
      "jest-watch-typeahead/testname"
    ],
    "resetMocks": true
  },
  "babel": {
    "presets": [
      "react-app"
    ]
  },
  "devDependencies": {
    "less": "^4.1.3",
    "less-loader": "^6.0.0"
  }
}

Solution:

The dependent (@testing-library/react) version is relatively low, and it is useless. Just delete it and restart your computer.

Here is the package.json file after you solved the error

{
  "name": "@testing-library/jest-dom",
  "version": "5.16.5",
  "description": "Custom jest matchers to test the state of the DOM",
  "main": "dist/index.js",
  "engines": {
    "node": ">=8",
    "npm": ">=6",
    "yarn": ">=1"
  },
  "scripts": {
    "build": "kcd-scripts build",
    "format": "kcd-scripts format",
    "lint": "kcd-scripts lint",
    "setup": "npm install && npm run validate -s",
    "test": "kcd-scripts test",
    "test:update": "npm test -- --updateSnapshot --coverage",
    "validate": "kcd-scripts validate"
  },
  "files": [
    "dist",
    "extend-expect.js",
    "matchers.js"
  ],
  "keywords": [
    "testing",
    "dom",
    "jest",
    "jsdom"
  ],
  "author": "Ernesto Garcia <[email protected]> (http://gnapse.github.io)",
  "license": "MIT",
  "dependencies": {
    "@babel/runtime": "^7.9.2",
    "@types/testing-library__jest-dom": "^5.9.1",
    "aria-query": "^5.0.0",
    "chalk": "^3.0.0",
    "@adobe/css-tools": "^4.0.1",
    "css.escape": "^1.5.1",
    "dom-accessibility-api": "^0.5.6",
    "lodash": "^4.17.15",
    "redent": "^3.0.0"
  },
  "devDependencies": {
    "jest-environment-jsdom-sixteen": "^1.0.3",
    "jest-watch-select-projects": "^2.0.0",
    "jsdom": "^16.2.1",
    "kcd-scripts": "^11.1.0",
    "pretty-format": "^25.1.0"
  },
  "eslintConfig": {
    "extends": "./node_modules/kcd-scripts/eslint.js",
    "rules": {
      "@babel/no-invalid-this": "off"
    },
    "overrides": [
      {
        "files": [
          "src/__tests__/*.js"
        ],
        "rules": {
          "max-lines-per-function": "off"
        }
      }
    ]
  },
  "eslintIgnore": [
    "node_modules",
    "coverage",
    "dist"
  ],
  "repository": {
    "type": "git",
    "url": "https://github.com/testing-library/jest-dom"
  },
  "bugs": {
    "url": "https://github.com/testing-library/jest-dom/issues"
  },
  "homepage": "https://github.com/testing-library/jest-dom#readme"
}

[Solved] vite2+vue3 jsx Error: React is not defined

Vite2 + vue3 uses JSX to report an error: react is not defined

If JSX is not used in react, for error reporting:

React is not defined

It is required to add the following configuration to the vite.config.js file:

export default {
  esbuild: {
    jsxFactory: 'h',
    jsxFragment: 'Fragment',
    jsxInject: "import { h } from 'vue';"
  }
}

The last sentence is equivalent to the injection of vite. The helper automatically introduces h

[Solved] Error:The above error occurred in one of your React components & A component suspended while respondi

lazyLoad of routing components, lazy loading problem, when using the lazy function of react in conjunction with the import() function to dynamically load routing components.

import React, { Component, lazy } from 'react'
·······

const Login = lazy(()=>import('XXXX'))

The following errors will be reported:

Error analysis: suspended=> When the network speed is slow and the specified routing component page is not loaded, you need to use the fallback in suspend to load the contents of the fallback before the specified page appears.

Solution:

import React, { Component, lazy,Suspense } from 'react'
·····

const Home = lazy(()=> import('./Home'))
const About = lazy(()=> import('./About'))

·······
<Suspense fallback={<h2>Loading..</h2>}>
  <Routes>
     <Route path="/about" element={<About/>}/>
     <Route path="/home" element={<Home/>}/>
   </Routes>
</Suspense>

[Solved] React Startup Error at the First time :SyntaxError: Unexpected token

[react] prompt syntaxerror: unexpected token

1. background

Use react scaffold to build the project

  • Install globally: npm i -g create-react-app
  • create-react-app hello-react
  • Go to the project folder: cd hello-react
  • Start the project: npm start

When executing npm start, an error occurred, please check the node version.

 

2. problem-solving

  • The investigation found that it was caused by the node version.
  • execute node -v ;

  • react-app requires node version greater than 14
  • execute nvm use 14;

  • Just restart.

JavaScript Common Errors List (Reasons & Solutions)

Here is a list of the most common errors in JavaScript.

 

JavaScript Common Errors List

1.Uncaught TypeError: Cannot read property

Improper initialization of the state when reading the properties of an undefined object or calling its methods or rendering UI components will appear in the console

The simplest Solution: initialize state in the constructor.

2. TypeError: ‘undefined’ is not an object

An error occurred while reading a property or calling a method on an undefined object in safari.

3. TypeError: null is not an object

An error occurred while reading a property or calling a method on an empty object in Safari

Note: in JavaScript, null and undefined are different, which is why we see two different error messages. Undefined is usually a variable that has not been allocated, and null means the value is empty.

4.  (unknown): Script error

This kind of script error occurs when an uncaught JavaScript error (an error caused by the window.oneror handler rather than captured in the try catch) is restricted by the browser’s cross domain policy.

5. TypeError: Object doesn’t support property

The error in ie when calling an undefined method is equivalent to the “typeerror:” undefined “isnotafunction” error in chrome.

6. TypeError: ‘undefined’ is not a function

This is an error in chrome when calling an undefined function.

7. Uncaught RangeError

This error occurs when calling a recursive function that does not terminate, or if you pass a value to a function that is out of range.

8. TypeError: Cannot read property ‘length’

An error occurred while reading the length attribute of an undefined variable.

9. Uncaught TypeError: Cannot set property

When accessing an undefined variable, it always returns undefined. We cannot get or set any undefined properties.

10. ReferenceError: event is not defined

This error is raised when a variable is undefined or is outside the current scope.

[Solved] vue Project Error: react lazy eslint error Parsing error: Unexpected token import

vue Project Error: react lazy eslint error Parsing error: Unexpected token import

1. You need to install the extension component eslint, and then click settings in settings – extension search – eslintrc and add this line (“parser”: “Babel-eslint”) in settings.json, save the code, and then run the project

[Solved] React Click the Event to Modify the State Value Error

React Click the Event to Modify the State Value Error

Make a mistake.

Cannot read properties of undefined (reading ‘setstate’) when updating the state value

import React from "react";
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: "Hello",
    };
    //Modify the codes behind this line
    
    //Modify the codes before this line
  }
  handleClick() {
    this.setState({
      text: "You clicked!",
    });
  }

  render() {
    return (
      <div>
        {/* Modify the codes behind this line */}
        <button onClick={this.handleClick}>Click Me</button>
        {/* Modify the codes before this line */}
        <h1>{this.state.text}</h1>
      </div>
    );
  }
}
export default MyComponent;

An error is reported when updating the state value,

Cannot read properties of undefined (reading ‘setState’)

It seems that the direction of this needs to be changed. I don’t quite understand it.

    // Modify the codes behind this line
    this.handleClick = this.handleClick.bind(this);
    // Modify the codes before this line

Value update after clicking

Another method is to modify it into an arrow function

  handleClick = () => {
    this.setState({
      text: "You clicked!",
    });
  };

The modified value can still be realized

React: How to Solve Web3 import error

How to Solve Web3 import error

Error Messages:
Solution:
Web3 and Create-react-app
If you are using create-react-app version >=5 you may run into issues building. This is because NodeJS polyfills are not included in the latest version of create-react-app.
Solution:
Install react-app-rewired and the missing modules
1. Down the Dependency below
yarn:
If you are using yarn:

yarn add --dev react-app-rewired process crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer

npm:
If you are using npm:

npm install --save-dev react-app-rewired crypto-browserify stream-browserify assert stream-http https-browserify os-browserify url buffer process

Create config-overrides.js in the root of your project folder with the content
2. Create config-overrides.js file in the main directory:

const webpack = require('webpack');

module.exports = function override(config) {
    const fallback = config.resolve.fallback || {};
    Object.assign(fallback, {
        "crypto": require.resolve("crypto-browserify"),
        "stream": require.resolve("stream-browserify"),
        "assert": require.resolve("assert"),
        "http": require.resolve("stream-http"),
        "https": require.resolve("https-browserify"),
        "os": require.resolve("os-browserify"),
        "url": require.resolve("url")
    })
    config.resolve.fallback = fallback;
    config.plugins = (config.plugins || []).concat([
        new webpack.ProvidePlugin({
            process: 'process/browser',
            Buffer: ['buffer', 'Buffer']
        })
    ])
    return config;
}

3.Modify package.json
Within package.json change the scripts field for start, build and test. Instead of react-scripts replace it with react-app-rewired
before:
Before:

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

After change:

"scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
},

4.Close the warning in the terminal
The missing Nodejs polyfills should be included now and your app should be functional with web3.
If you want to hide the warnings created by the console:
In config-overrides.js within the override function, add:
Add the following code in override method of config-overrides.js

config.ignoreWarnings = [/Failed to parse source map/];

The above contents are the processing methods on Web3 GIT