react | The library for web and native user interfaces | Frontend Framework library
kandi X-RAY | react Summary
Support
Quality
Security
License
Reuse
- Updates the root state of the Fiber context .
- Initialize a new child .
- Visits the given function node .
- Sends the fiber in the current fiber .
- Creates a new auto sized canvas .
- Creates the panel if needed .
- Creates internal properties .
- Commit mutations on a fiber .
- Process a component .
- Commits the fiber effect .
react Key Features
react Examples and Code Snippets
useEffect(() => {
fetch("https://www.breakingbadapi.com/api/characters")
.then(response => response.json()) // <-- wait for Promise to resolve
.then(characters => setCharacters(characters)
.catch(err => {
console.log("There must have been an error somewhere in your code", err.message)
});
}, []); // <-- add empty dependency array
useEffect(() => {
const getData = async () => {
try {
const response = await fetch("https://www.breakingbadapi.com/api/characters");
const characters = await response.json(); // <-- wait for Promise to resolve
setCharacters(characters);
} catch(err) {
console.log("There must have been an error somewhere in your code", err?.message);
};
}
getData();
}, []); // <-- add empty dependency array
{characters.map((character) => (
// <-- Add React key to outer element
))}
React.useEffect(() => {
const interval = setInterval(() => {
setValue((v) => {
return v === 4 ? 0 : v + 1;
});
}, 1000);
return () => clearInterval(interval);
}, []);
import React from "react";
const colors = ["#92c952", "#771796", "#24f355", "#d32776", "#f66b97"];
const images = [
"https://via.placeholder.com/150/92c952",
"https://via.placeholder.com/150/771796",
"https://via.placeholder.com/150/24f355",
"https://via.placeholder.com/150/d32776",
"https://via.placeholder.com/150/f66b97"
];
export default function App() {
const [value, setValue] = React.useState(0);
React.useEffect(() => {
const interval = setInterval(() => {
setValue((v) => {
return v === 4 ? 0 : v + 1;
});
}, 1000);
return () => clearInterval(interval);
}, []);
return (
);
}
// ListOfMeds.jsx
export const getSpecificMedicineWithId = (number) => {
const mockListOfMedicines = [
{
medicineName: "Augmentin 625 Duo Tablet",
medicineId: "D06ID232435454",
groupName: "Generic Medicine",
stock: 350,
},
{
medicineName: "Augmentin 625 Duo Tablet",
medicineId: "D06ID232435454",
groupName: "Generic Medicine",
stock: 350,
},
];
const filteredData = mockListOfMedicines.find((medicine) => {
return medicine.medicineId === number;
});
return filteredData;
};
const ListOfMeds = () => {
return
};
export default ListOfMeds;
// MedicineInfo.jsx
import React from "react";
import { useParams } from "react-router-dom";
import { getSpecificMedicineWithId } from "./ListOfMeds";
const MedicineInfo = () => {
let params = useParams();
const medicine = getSpecificMedicineWithId(parrams.medicineId);
return MedicineId: {params.medicineId};
};
export default MedicineInfo;
import React { useState } from "react";
function App() {
const [isTextHidden, setTextHidden] = useState(true);
const onClick = () => setTextHidden(!isTextHidden);
return (
{isTextHidden ? 'Show' : 'Hide'}
{!textHidden ? : null}
);
}
const Text = () => I will disappear, true Magic;
export default App;
import React from 'react';
import ReactDOM from 'react-dom/client';
const root = ReactDOM.createRoot(document.getElementById('root'));
const title = Draft;
let numPlay;
const numPlayers = (
{title}
How many players would you like to draft with?
Confirm
);
function getConfirm() {
numPlay = document.getElementById('numPlay');
root.render(nextPage);
}
const nextPage = (
{title}
How many draftees are there?
{numPlay}
);
root.render(numPlayers);
import React from 'react';
import './CardBus.style.css';
import TimeProgressThin from '../../icon/Time_progress_thin.svg';
import PinLight from '../../icon/Pin_light_thin.svg';
function CardBus(props) {
const [isSelected, setIsSelected] = useState(false);
let { eachBus, buses, setBuses} = props;
React.useEffect(() => {
setIsSelected(eachBus.isSelected);
}, [props]);
const selectedHandler = () => {
let item = buses.find(bus=> bus.busNumber === eachBus.busNumber);
let index = buses.findIndex(bus=> bus.busNumber === eachBus.busNumber);
item.isSelected = !item.isSelected;
let newData = buses;
newData[index] = item;
setBuses(newData);
}
return (
{eachBus.busNumber}
{`Armada ${eachBus.busNumber}`}
{eachBus.destination}
Last stopped
{eachBus.stopTime}
Location Stopped
{eachBus.stopLocation}
);
}
export default CardBus;
import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";
const image = { uri: "https://reactjs.org/logo-og.png" };
const App = () => (
The text you want to display
);
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
justifyContent: "center"
},
text: {
color: "white",
fontSize: 42,
lineHeight: 84,
fontWeight: "bold",
textAlign: "center",
backgroundColor: "#000000c0"
}
});
export default App;
Trending Discussions on react
Trending Discussions on react
QUESTION
I am getting this create React app error again and again even after doing the uninstall part.
npm uninstall -g create-react-app
up to date, audited 1 package in 570ms
found 0 vulnerabilities
npx create-react-app test-app
Need to install the following packages: create-react-app Ok to proceed? (y) y
You are running
create-react-app
4.0.3, which is behind the latest release (5.0.0).We no longer support global installation of Create React App.
Please remove any global installs with one of the following commands:
- npm uninstall -g create-react-app
- yarn global remove create-react-app
The latest instructions for creating a new app can be found here: https://create-react-app.dev/docs/getting-started/
C:\>npm --version
8.3.0
C:\>node --version
v16.13.0
How can I fix this?
ANSWER
Answered 2022-Jan-01 at 22:34You will have to clear the npx cache to make it work.
You can locate the location of the folder where create-react-app is installed using npm ls -g create-react-app
.
Also, to clear the cache, refer to this answer in How can I clear the central cache for `npx`?
QUESTION
I created the default IntelliJ IDEA React project and got this:
Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:67:19)
at Object.createHash (node:crypto:130:10)
at module.exports (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/util/createHash.js:135:53)
at NormalModule._initBuildHash (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:417:16)
at handleParseError (/Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:471:10)
at /Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:503:5
at /Users/user/Programming Documents/WebServer/untitled/node_modules/webpack/lib/NormalModule.js:358:12
at /Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:373:3
at iterateNormalLoaders (/Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
at iterateNormalLoaders (/Users/user/Programming Documents/WebServer/untitled/node_modules/loader-runner/lib/LoaderRunner.js:221:10)
/Users/user/Programming Documents/WebServer/untitled/node_modules/react-scripts/scripts/start.js:19
throw err;
^
It seems to be a recent issue - webpack ran into this 4 days ago and is still working on it.
ANSWER
Answered 2021-Nov-15 at 00:32Failed to construct transformer: Error: error:0308010C:digital envelope routines::unsupported
The simplest and easiest solution to solve the above error is to downgrade Node.js to v14.18.1. And then just delete folder node_modules
and try to rebuild your project and your error must be solved.
QUESTION
I have updated node
today and I'm getting this error:
error: TypeError: Cannot read properties of undefined (reading 'transformFile')
at Bundler.transformFile (/Users/.../node_modules/metro/src/Bundler.js:48:30)
at runMicrotasks ()
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.transform (/Users/.../node_modules/metro/src/lib/transformHelpers.js:101:12)
at async processModule (/Users/.../node_modules/metro/src/DeltaBundler/traverseDependencies.js:137:18)
at async traverseDependenciesForSingleFile (/Users/.../node_modules/metro/src/DeltaBundler/traverseDependencies.js:131:3)
at async Promise.all (index 0)
at async initialTraverseDependencies (/Users/.../node_modules/metro/src/DeltaBundler/traverseDependencies.js:114:3)
at async DeltaCalculator._getChangedDependencies (/Users/.../node_modules/metro/src/DeltaBundler/DeltaCalculator.js:164:25)
at async DeltaCalculator.getDelta (/Users/.../node_modules/metro/src/DeltaBundler/DeltaCalculator.js:94:16)
Other than that I haven't done anything unusual, so I'm not sure what to share. If I'm missing any info please comment and I'll add it.
While building the terminal also throws this error:
Failed to construct transformer: Error: error:0308010C:digital envelope routines::unsupported
at new Hash (node:internal/crypto/hash:67:19)
at Object.createHash (node:crypto:130:10)
at stableHash (/Users/.../node_modules/metro-cache/src/stableHash.js:19:8)
at Object.getCacheKey (/Users/.../node_modules/metro-transform-worker/src/index.js:593:7)
at getTransformCacheKey (/Users/.../node_modules/metro/src/DeltaBundler/getTransformCacheKey.js:24:19)
at new Transformer (/Users/.../node_modules/metro/src/DeltaBundler/Transformer.js:48:9)
at /Users/.../node_modules/metro/src/Bundler.js:22:29
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
opensslErrorStack: [ 'error:03000086:digital envelope routines::initialization error' ],
library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'
}
My node, npx and react-native versions are:
- node: 17.0.0
- npx: 8.1.0
- react-native-cli: 2.0.1
ANSWER
Answered 2021-Oct-27 at 17:19Ran into the same issue with Node.js 17.0.0. To solve it, I downgraded to version 14.18.1, deleted node_modules
and reinstalled.
QUESTION
I have been using github actions for quite sometime but today my deployments started failing. Below is the error from github action logs
Command: git
Arguments: ls-remote --tags --heads git://github.com/adobe-webplatform/eve.git
Directory: /home/runner/work/stackstream-fe/stackstream-fe
Output:
fatal: remote error:
The unauthenticated git protocol on port 9418 is no longer supported.
Upon investigation, it appears that below section in my yml file is causing the issue.
- name: Installing modules
run: yarn install
I have looked into this change log but can't seem to comprehend the issue.
Additional Details: Server: EC2 Instance Github actions steps:
steps:
- name: Checkout
uses: actions/checkout@v2
- id: vars
run: |
if [ '${{ github.ref }}' == 'refs/heads/master' ]; then echo "::set-output name=environment::prod_stackstream" ; echo "::set-output name=api-url::api" ; elif [ '${{ github.ref }}' == 'refs/heads/staging' ]; then echo "::set-output name=environment::staging_stackstream" ; echo "::set-output name=api-url::stagingapi" ; else echo "::set-output name=environment::dev_stackstream" ; echo "::set-output name=api-url::devapi" ; fi
- uses: pCYSl5EDgo/cat@master
id: slack
with:
path: .github/workflows/slack.txt
- name: Slack Start Notification
uses: 8398a7/action-slack@v3
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }}
ENVIRONMENT: '`${{ steps.vars.outputs.environment }}`'
COLOR: good
STATUS: '`Started`'
with:
status: custom
fields: workflow,job,commit,repo,ref,author,took
custom_payload: |
${{ steps.slack.outputs.text }}
- name: Installing modules
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn install
- name: Create Frontend Build
env:
REACT_APP_API_URL: 'https://${{ steps.vars.outputs.api-url }}mergestack.com/api/v1'
run: yarn build
- name: Deploy to Frontend Server DEV
if: ${{ contains(github.ref, 'dev') }}
uses: easingthemes/ssh-deploy@v2.1.5
env:
SSH_PRIVATE_KEY: ${{ secrets.DEV_KEY }}
ARGS: '-rltgoDzvO --delete'
SOURCE: 'deploy/'
REMOTE_HOST: ${{ secrets.DEV_HOST }}
REMOTE_USER: plyfolio-dev
TARGET: '/home/plyfolio-dev/${{ steps.vars.outputs.environment }}/fe/deploy'
package.json file
{
"name": "stackstream-fe",
"version": "1.0.0",
"authors": [
"fayyaznofal@gmail.com"
],
"private": true,
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.34",
"@fortawesome/free-solid-svg-icons": "^5.15.2",
"@fortawesome/react-fontawesome": "^0.1.14",
"@fullcalendar/bootstrap": "^5.5.0",
"@fullcalendar/core": "^5.5.0",
"@fullcalendar/daygrid": "^5.5.0",
"@fullcalendar/interaction": "^5.5.0",
"@fullcalendar/react": "^5.5.0",
"@lourenci/react-kanban": "^2.1.0",
"@redux-saga/simple-saga-monitor": "^1.1.2",
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^11.2.3",
"@testing-library/user-event": "^12.6.0",
"@toast-ui/react-chart": "^1.0.2",
"@types/jest": "^26.0.14",
"@types/node": "^14.10.3",
"@types/react": "^16.9.49",
"@types/react-dom": "^16.9.8",
"@vtaits/react-color-picker": "^0.1.1",
"apexcharts": "^3.23.1",
"availity-reactstrap-validation": "^2.7.0",
"axios": "^0.21.1",
"axios-mock-adapter": "^1.19.0",
"axios-progress-bar": "^1.2.0",
"bootstrap": "^5.0.0-beta2",
"chart.js": "^2.9.4",
"chartist": "^0.11.4",
"classnames": "^2.2.6",
"components": "^0.1.0",
"dotenv": "^8.2.0",
"draft-js": "^0.11.7",
"echarts": "^4.9.0",
"echarts-for-react": "^2.0.16",
"firebase": "^8.2.3",
"google-maps-react": "^2.0.6",
"history": "^4.10.1",
"i": "^0.3.6",
"i18next": "^19.8.4",
"i18next-browser-languagedetector": "^6.0.1",
"jsonwebtoken": "^8.5.1",
"leaflet": "^1.7.1",
"lodash": "^4.17.21",
"lodash.clonedeep": "^4.5.0",
"lodash.get": "^4.4.2",
"metismenujs": "^1.2.1",
"mkdirp": "^1.0.4",
"moment": "2.29.1",
"moment-timezone": "^0.5.32",
"nouislider-react": "^3.3.9",
"npm": "^7.6.3",
"prop-types": "^15.7.2",
"query-string": "^6.14.0",
"react": "^16.13.1",
"react-apexcharts": "^1.3.7",
"react-auth-code-input": "^1.0.0",
"react-avatar": "^3.10.0",
"react-bootstrap": "^1.5.0",
"react-bootstrap-editable": "^0.8.2",
"react-bootstrap-sweetalert": "^5.2.0",
"react-bootstrap-table-next": "^4.0.3",
"react-bootstrap-table2-editor": "^1.4.0",
"react-bootstrap-table2-paginator": "^2.1.2",
"react-bootstrap-table2-toolkit": "^2.1.3",
"react-chartist": "^0.14.3",
"react-chartjs-2": "^2.11.1",
"react-color": "^2.19.3",
"react-confirm-alert": "^2.7.0",
"react-content-loader": "^6.0.1",
"react-countdown": "^2.3.1",
"react-countup": "^4.3.3",
"react-cropper": "^2.1.4",
"react-data-table-component": "^6.11.8",
"react-date-picker": "^8.0.6",
"react-datepicker": "^3.4.1",
"react-dom": "^16.13.1",
"react-draft-wysiwyg": "^1.14.5",
"react-drag-listview": "^0.1.8",
"react-drawer": "^1.3.4",
"react-dropzone": "^11.2.4",
"react-dual-listbox": "^2.0.0",
"react-facebook-login": "^4.1.1",
"react-flatpickr": "^3.10.6",
"react-google-login": "^5.2.2",
"react-hook-form": "^7.15.2",
"react-i18next": "^11.8.5",
"react-icons": "^4.2.0",
"react-image-lightbox": "^5.1.1",
"react-input-mask": "^2.0.4",
"react-jvectormap": "^0.0.16",
"react-leaflet": "^3.0.5",
"react-meta-tags": "^1.0.1",
"react-modal-video": "^1.2.6",
"react-notifications": "^1.7.2",
"react-number-format": "^4.7.3",
"react-perfect-scrollbar": "^1.5.8",
"react-rangeslider": "^2.2.0",
"react-rating": "^2.0.5",
"react-rating-tooltip": "^1.1.6",
"react-redux": "^7.2.1",
"react-responsive-carousel": "^3.2.11",
"react-router-dom": "^5.2.0",
"react-script": "^2.0.5",
"react-scripts": "3.4.3",
"react-select": "^4.3.1",
"react-sparklines": "^1.7.0",
"react-star-ratings": "^2.3.0",
"react-super-responsive-table": "^5.2.0",
"react-switch": "^6.0.0",
"react-table": "^7.6.3",
"react-toastify": "^7.0.3",
"react-toastr": "^3.0.0",
"react-twitter-auth": "0.0.13",
"reactstrap": "^8.8.1",
"recharts": "^2.0.8",
"redux": "^4.0.5",
"redux-saga": "^1.1.3",
"reselect": "^4.0.0",
"sass": "^1.37.5",
"simplebar-react": "^2.3.0",
"styled": "^1.0.0",
"styled-components": "^5.2.1",
"toastr": "^2.1.4",
"typescript": "^4.0.2",
"universal-cookie": "^4.0.4"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^2.27.0",
"@typescript-eslint/parser": "^2.27.0",
"@typescript-eslint/typescript-estree": "^4.15.2",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.2",
"husky": "^4.2.5",
"lint-staged": "^10.1.3",
"prettier": "^1.19.1",
"react-test-renderer": "^16.13.1",
"redux-devtools-extension": "^2.13.8",
"redux-mock-store": "^1.5.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && mv build ./deploy/build",
"build-local": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,ts,tsx}": [
"eslint --fix"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
ANSWER
Answered 2022-Mar-16 at 07:01First, this error message is indeed expected on Jan. 11th, 2022.
See "Improving Git protocol security on GitHub".
January 11, 2022 Final brownout.
This is the full brownout period where we’ll temporarily stop accepting the deprecated key and signature types, ciphers, and MACs, and the unencrypted Git protocol.
This will help clients discover any lingering use of older keys or old URLs.
Second, check your package.json
dependencies for any git://
URL, as in this example, fixed in this PR.
As noted by Jörg W Mittag:
For GitHub Actions:There was a 4-month warning.
The entire Internet has been moving away from unauthenticated, unencrypted protocols for a decade, it's not like this is a huge surprise.Personally, I consider it less an "issue" and more "detecting unmaintained dependencies".
Plus, this is still only the brownout period, so the protocol will only be disabled for a short period of time, allowing developers to discover the problem.
The permanent shutdown is not until March 15th.
As in actions/checkout issue 14, you can add as a first step:
- name: Fix up git URLs
run: echo -e '[url "https://github.com/"]\n insteadOf = "git://github.com/"' >> ~/.gitconfig
That will change any git://github.com/
into https://github.com/
.
For all your repositories, you can set:
git config --global url."https://github.com/".insteadOf git://github.com/
You can also use SSH, but GitHub Security reminds us that, as of March 15th, 2022, GitHub stopped accepting DSA keys. RSA keys uploaded after Nov 2, 2021 will work only with SHA-2 signatures.
The deprecated MACs, ciphers, and unencrypted Git protocol are permanently disabled.
So this (with the right key) would work:
git config --global url."git@github.com:".insteadOf git://github.com/
That will change any git://github.com/
(unencrypted Git protocol) into git@github.com:
(SSH URL).
QUESTION
I am trying to upgrade to React Router v6 (react-router-dom 6.0.1
).
Here is my updated code:
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
} />
} />
} />
The last Route
is redirecting the rest of paths to /
.
However, I got an error
TS2322: Type '{ render: () => Element; }' is not assignable to type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'. Property 'render' does not exist on type 'IntrinsicAttributes & (PathRouteProps | LayoutRouteProps | IndexRouteProps)'.
However, based on the doc, it does have render
for Route
. How to use it correctly?
ANSWER
Answered 2022-Mar-18 at 18:41I think you should use the no match route approach.
Check this in the documentation.
https://reactrouter.com/docs/en/v6/getting-started/tutorial#adding-a-no-match-route
import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';
} />
} />
}
/>
To keep the history clean, you should set replace
prop. This will avoid extra redirects after the user click back. Thanks @Paul for this tip.
QUESTION
I'm using React Router v6 and am creating private routes for my application.
In file PrivateRoute.js, I've the code
import React from 'react';
import {Route,Navigate} from "react-router-dom";
import {isauth} from 'auth'
function PrivateRoute({ element, path }) {
const authed = isauth() // isauth() returns true or false based on localStorage
const ele = authed === true ? element : ;
return ;
}
export default PrivateRoute
And in file route.js I've written as:
...
}/>
}/>
I've gone through the same example React-router Auth Example - StackBlitz, file App.tsx
Is there something I'm missing?
ANSWER
Answered 2021-Nov-12 at 21:20I ran into the same issue today and came up with the following solution based on this very helpful article by Andrew Luca
In PrivateRoute.js:
import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoute = () => {
const auth = null; // determine if authorized, from context or however you're doing it
// If authorized, return an outlet that will render child elements
// If not, return element that will navigate to login page
return auth ? : ;
}
In App.js (I've left in some other pages as examples):
import './App.css';
import React, {Fragment} from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Home from './components/pages/Home';
import Register from './components/auth/Register'
import Login from './components/auth/Login';
import PrivateRoute from './components/routing/PrivateRoute';
const App = () => {
return (
}>
}/>
}/>
}/>
);
}
In the above routing, this is the private route:
}>
}/>
If authorization is successful, the element will show. Otherwise, it will navigate to the login page.
QUESTION
I cannot resolve the issue. When application loads react native throw warnings. new NativeEventEmitter()
was called with a non-null argument without the required addListener
method. WARN new NativeEventEmitter()
was called with a non-null argument without the required removeListeners
method.
ANSWER
Answered 2021-Nov-24 at 11:07This is likely due to the newest version of react-native. A lot of libraries still haven't released a new version to handle these warnings (or errors in some case). Examples include https://github.com/react-navigation/react-navigation/issues/9882 and https://github.com/APSL/react-native-keyboard-aware-scroll-view/pull/501. If it bothers you, you can hide the warning for now (source):
import { LogBox } from 'react-native';
LogBox.ignoreLogs(['new NativeEventEmitter']); // Ignore log notification by message
LogBox.ignoreAllLogs(); //Ignore all log notifications
QUESTION
I am currently setting up a boilerplate with React, Typescript, styled components, webpack etc. and I am getting an error when trying to run eslint:
Error: Must use import to load ES Module
Here is a more verbose version of the error:
/Users/ben/Desktop/development projects/react-boilerplate-styled-context/src/api/api.ts
0:0 error Parsing error: Must use import to load ES Module: /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js
require() of ES modules is not supported.
require() of /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/lib/definition.js from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/babel-eslint/lib/require-from-eslint.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename definition.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/ben/Desktop/development projects/react-boilerplate-styled-context/node_modules/eslint/node_modules/eslint-scope/package.json
The error occurs in every single one of my .js and .ts/ .tsx files where I only use import
or the file doesn't even have an import at all. I understand what the error is saying but I have no idea why it is being thrown when in fact I only use imports or even no imports at all in some files.
Here is my package.json where I trigger the linter from using npm run lint:eslint:quiet
:
{
"name": "my-react-boilerplate",
"version": "1.0.0",
"description": "",
"main": "index.tsx",
"directories": {
"test": "test"
},
"engines": {
"node": ">=14.0.0"
},
"type": "module",
"scripts": {
"build": "webpack --config webpack.prod.js",
"dev": "webpack serve --config webpack.dev.js",
"lint": "npm run typecheck && npm run lint:css && npm run lint:eslint:quiet",
"lint:css": "stylelint './src/**/*.{js,ts,tsx}'",
"lint:eslint:quiet": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern --quiet",
"lint:eslint": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern",
"lint:eslint:fix": "eslint --ext .ts,.tsx,.js,.jsx ./src --no-error-on-unmatched-pattern --quiet --fix",
"test": "cross-env NODE_ENV=test jest --coverage",
"test:watch": "cross-env NODE_ENV=test jest --watchAll",
"typecheck": "tsc --noEmit",
"precommit": "npm run lint"
},
"lint-staged": {
"*.{ts,tsx,js,jsx}": [
"npm run lint:eslint:fix",
"git add --force"
],
"*.{md,json}": [
"prettier --write",
"git add --force"
]
},
"husky": {
"hooks": {
"pre-commit": "npx lint-staged && npm run typecheck"
}
},
"resolutions": {
"styled-components": "^5"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.5.4",
"@babel/plugin-proposal-class-properties": "^7.5.0",
"@babel/preset-env": "^7.5.4",
"@babel/preset-react": "^7.0.0",
"@types/history": "^4.7.6",
"@types/react": "^17.0.29",
"@types/react-dom": "^17.0.9",
"@types/react-router": "^5.1.17",
"@types/react-router-dom": "^5.1.5",
"@types/styled-components": "^5.1.15",
"@typescript-eslint/eslint-plugin": "^5.0.0",
"babel-cli": "^6.26.0",
"babel-eslint": "^10.0.2",
"babel-loader": "^8.0.0-beta.6",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"clean-webpack-plugin": "^4.0.0",
"dotenv-webpack": "^7.0.3",
"error-overlay-webpack-plugin": "^1.0.0",
"eslint": "^8.0.0",
"eslint-config-airbnb": "^18.2.0",
"eslint-config-prettier": "^8.3.0",
"eslint-config-with-prettier": "^6.0.0",
"eslint-plugin-compat": "^3.3.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-jsx-a11y": "^6.2.3",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-react-hooks": "^4.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.2",
"husky": "^7.0.2",
"prettier": "^2.4.1",
"raw-loader": "^4.0.2",
"style-loader": "^3.3.0",
"stylelint": "^13.13.1",
"stylelint-config-recommended": "^5.0.0",
"stylelint-config-styled-components": "^0.1.1",
"stylelint-processor-styled-components": "^1.10.0",
"ts-loader": "^9.2.6",
"tslint": "^6.1.3",
"typescript": "^4.4.4",
"url-loader": "^4.1.1",
"webpack": "^5.58.2",
"webpack-cli": "^4.2.0",
"webpack-dev-server": "^4.3.1",
"webpack-merge": "^5.3.0"
},
"dependencies": {
"history": "^4.10.0",
"process": "^0.11.10",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-router-dom": "^5.2.0",
"styled-components": "^5.2.1"
}
}
Here is my .eslintrc file:
{
"extends": ["airbnb", "prettier"],
"parser": "babel-eslint",
"plugins": ["prettier", "@typescript-eslint"],
"parserOptions": {
"ecmaVersion": 8,
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"impliedStrict": true,
"classes": true
}
},
"env": {
"browser": true,
"node": true,
"jest": true
},
"rules": {
"arrow-body-style": ["error", "as-needed"],
"class-methods-use-this": 0,
"react/jsx-filename-extension": 0,
"global-require": 0,
"react/destructuring-assignment": 0,
"import/named": 2,
"linebreak-style": 0,
"import/no-dynamic-require": 0,
"import/no-named-as-default": 0,
"import/no-unresolved": 2,
"import/prefer-default-export": 0,
"semi": [2, "always"],
"max-len": [
"error",
{
"code": 80,
"ignoreUrls": true,
"ignoreComments": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true
}
],
"new-cap": [
2,
{
"capIsNew": false,
"newIsCap": true
}
],
"no-param-reassign": 0,
"no-shadow": 0,
"no-tabs": 2,
"no-underscore-dangle": 0,
"react/forbid-prop-types": [
"error",
{
"forbid": ["any"]
}
],
"import/no-extraneous-dependencies": ["error", { "devDependencies": true }],
"react/jsx-no-bind": [
"error",
{
"ignoreRefs": true,
"allowArrowFunctions": true,
"allowBind": false
}
],
"react/no-unknown-property": [
2,
{
"ignore": ["itemscope", "itemtype", "itemprop"]
}
]
}
}
And i'm not sure if relevant but also my tsconfig.eslint.json file:
{
"extends": "./tsconfig.json",
"include": ["./src/**/*.ts", "./src/**/*.tsx", "./src/**/*.js"],
"exclude": ["node_modules/**", "build/**", "coverage/**"]
}
Not sure if anyone has come across this before? Googling the error does not present any useful forums or raised bugs, most of them just state not to use require
in your files which I am not.
ANSWER
Answered 2022-Mar-15 at 16:08I think the problem is that you are trying to use the deprecated babel-eslint parser, last updated a year ago, which looks like it doesn't support ES6 modules. Updating to the latest parser seems to work, at least for simple linting.
So, do this:
- In package.json, update the line
"babel-eslint": "^10.0.2",
to"@babel/eslint-parser": "^7.5.4",
. This works with the code above but it may be better to use the latest version, which at the time of writing is 7.16.3. - Run
npm i
from a terminal/command prompt in the folder - In .eslintrc, update the parser line
"parser": "babel-eslint",
to"parser": "@babel/eslint-parser",
- In .eslintrc, add
"requireConfigFile": false,
to the parserOptions section (underneath"ecmaVersion": 8,
) (I needed this or babel was looking for config files I don't have) - Run the command to lint a file
Then, for me with just your two configuration files, the error goes away and I get appropriate linting errors.
QUESTION
I'm trying to build a project in my M1,
but I got this error when I run npx react-native run-android
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
> The minCompileSdk (31) specified in a
dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
is greater than this module's compileSdkVersion (android-30).
Dependency: androidx.work:work-runtime:2.7.0-beta01.
AAR metadata file: /Users/macpro/.gradle/caches/transforms-3/999e9d813832e06d8f1b7de52647a502/transformed/work-runtime-2.7.0-beta01/META-INF/com/android/build/gradle/aar-metadata.properties.
Android/build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "30.0.0"
minSdkVersion = 21
compileSdkVersion = 30
targetSdkVersion = 30
supportLibVersion = "28.0.0"
}
repositories {
google()
jcenter()
}
dependencies {
classpath('com.android.tools.build:gradle:4.1.2')
classpath('com.google.gms:google-services:4.3.0')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
gradle-wrapper.properties
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.9-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
ANSWER
Answered 2021-Sep-02 at 23:03The error is being caused because one of your dependencies is internally using WorkManager 2.7.0-beta01 that was released today (which needs API 31). In my case it was CheckAarMetadata.kt
.
You can fix it by forcing Gradle to use an older version of Work Manager for the transitive dependency that works with API 30. In your build.gradle
file add:
dependencies {
def work_version = "2.6.0"
// Force WorkManager 2.6.0 for transitive dependency
implementation("androidx.work:work-runtime-ktx:$work_version") {
force = true
}
}
This should fix it.
QUESTION
I have been having a little bit of issues when deploying my create react app, as it fails to compile and tells me Plugin "react" was conflicted between "package.json » eslint-config-react-app »
I was wondering if somebody has encountered the same issue and knows how to solve it, thank you! I am still very new to all this.
ANSWER
Answered 2021-Dec-17 at 09:47There is a conflict in the casing
C:\Users\Ruben|desktop\reactapp\test.... whereas the nodemodules is looking for C:\Users\Ruben|Desktop\Reactapp\test....
This is a windows specific problem, and previously react would have run the app regardless of this difference. Not anymore it seems.
The solution I used was to locate the folder and open with code; that ensures that the path matches directly with what is stored in node modules
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install react
Use Online Playgrounds to get a taste of React.
Add React to a Website as a <script> tag in one minute.
Create a New React App if you're looking for a powerful JavaScript toolchain.
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page