babel decorator plugin not working - reactjs

I am trying to finstall the babel decorator plugin from their site at https://babeljs.io/docs/plugins/transform-decorators/ . I have followed all instructions as so to stop errors like this happening:
./src/components/pages/projectpages/dnd2/Card.js
Syntax error: Unexpected token (71:0)
69 | };
70 |
> 71 | #DropTarget(ItemTypes.CARD, cardTarget, connect => ({
| ^
72 | connectDropTarget: connect.dropTarget(),
73 | }))
74 | #DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({
I put this in my package.json
{
"plugins": ["transform-decorators"]
}
and run NPM Install and I still get the error, I'm not sure what else to do from this point and obviously I'm missing something. I'm posting my package.json here:
{
"name": "my-app",
"version": "0.1.0",
"stage": 0,
"private": true,
"dependencies": {
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"date-fns": "^1.28.5",
"dragula": "^3.7.2",
"flexbox-react": "^4.3.3",
"moment": "^2.18.1",
"moment-timezone": "^0.5.13",
"react": "^15.6.1",
"react-css-transition-replace": "^2.2.1",
"react-dnd": "^2.4.0",
"react-dnd-html5-backend": "^2.4.1",
"react-dom": "^15.6.1",
"react-dragula": "^1.1.17",
"react-fa": "^4.2.0",
"react-flexbox-grid": "^1.1.3",
"react-fontawesome": "^1.6.1",
"react-image-compare": "0.0.1",
"react-jsonschema-form": "^0.49.0",
"react-modal": "^1.9.4",
"react-moment": "^0.2.4",
"react-router-dom": "^4.1.1",
"react-toggle-display": "^2.2.0",
"react-transition-group": "^1.2.0",
"simple-react-forms": "^1.3.0",
"styled-components": "^1.4.6",
"styled-props": "^0.2.0"
},
"devDependencies": {
"babel-plugin-transform-decorators": "^6.24.1",
"babel-plugin-transform-decorators-legacy": "^1.3.4",
"react-scripts": "1.0.7"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"plugins": ["transform-decorators"]
}
and the component I'm getting there error is here with the # decorator
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import { DragSource, DropTarget } from 'react-dnd';
import ItemTypes from './ItemTypes';
const style = {
border: '1px dashed gray',
padding: '0.5rem 1rem',
marginBottom: '.5rem',
backgroundColor: 'white',
cursor: 'move',
};
const cardSource = {
beginDrag(props) {
return {
id: props.id,
index: props.index,
};
},
};
const cardTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().index;
const hoverIndex = props.index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
// Determine rectangle on screen
const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
// Get vertical middle
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
// Determine mouse position
const clientOffset = monitor.getClientOffset();
// Get pixels to the top
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return;
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return;
}
// Time to actually perform the action
props.moveCard(dragIndex, hoverIndex);
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
monitor.getItem().index = hoverIndex;
},
};
#DropTarget(ItemTypes.CARD, cardTarget, connect => ({
connectDropTarget: connect.dropTarget(),
}))
#DragSource(ItemTypes.CARD, cardSource, (connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
}))
export default class Card extends Component {
static propTypes = {
connectDragSource: PropTypes.func.isRequired,
connectDropTarget: PropTypes.func.isRequired,
index: PropTypes.number.isRequired,
isDragging: PropTypes.bool.isRequired,
id: PropTypes.any.isRequired,
text: PropTypes.string.isRequired,
moveCard: PropTypes.func.isRequired,
};
render() {
const { text, isDragging, connectDragSource, connectDropTarget } = this.props;
const opacity = isDragging ? 0 : 1;
return connectDragSource(connectDropTarget(
<div style={{ ...style, opacity }}>
{text}
</div>,
));
}
}
Can you please help me out figuring why I'm still getting the error here? Thank you!

If you're putting babel config in your package.json, put it inside a babel section, not at the top level.
"babel": {
"plugins": ["transform-decorators"]
}

Related

My Uppy suddenly gives me the error this.uppy.addFiles is not a function

I'm new to this and I get this error and can't figure out why please advice:
Looks like the Error is inside Uppy something.
I follow Uppy Tutorial docs like .use(Dashboard, {... and it was working but suddenly this error I try to back track but no luck
I add files from My Device and and then error happens no breakpoint are hit anywhere what I'm a missing
Here is my simple Uppy:
import React from "react";
import "#uppy/core/dist/style.css";
import "#uppy/status-bar/dist/style.css";
import "#uppy/drag-drop/dist/style.css";
import "#uppy/progress-bar/dist/style.css";
import "#uppy/dashboard/dist/style.css";
import "./styles.css";
const Uppy = require("#uppy/core");
// const Dashboard = require("#uppy/dashboard");
const GoogleDrive = require("#uppy/google-drive");
const Dropbox = require("#uppy/dropbox");
const Instagram = require("#uppy/instagram");
const Webcam = require("#uppy/webcam");
const Tus = require("#uppy/tus");
const {
Dashboard,
DashboardModal,
DragDrop,
ProgressBar,
} = require("#uppy/react");
class DashboardUppy extends React.Component {
constructor(props) {
super(props);
this.form = React.createRef();
this.state = {
showInlineDashboard: false,
open: false,
};
this.uppy = new Uppy({
id: "uppy1",
autoProceed: false,
debug: true,
allowMultipleUploads: true,
showSelectedFiles: true,
restrictions: {
maxFileSize: 1000000,
maxNumberOfFiles: 100,
minNumberOfFiles: 1,
allowedFileTypes: ['image/*', 'video/*'],
},
onBeforeFileAdded: (currentFile, files) => {
console.log(files);
const modifiedFile = Object.assign({}, currentFile, {
name: currentFile + Date.now(),
});
if (!currentFile.type) {
// log to console
this.uppy.log(`Skipping file because it has no type`);
// show error message to the user
this.uppy.info(`Skipping file because it has no type`, "error", 500);
return false;
}
return modifiedFile;
},
})
.use(Tus, { endpoint: "https://master.tus.io/files/" })
.use(GoogleDrive, { companionUrl: "https://companion.uppy.io" })
.use(Dropbox, {
companionUrl: "https://companion.uppy.io",
})
.use(Instagram, {
companionUrl: "https://companion.uppy.io",
})
.use(Webcam, {
onBeforeSnapshot: () => Promise.resolve(),
countdown: false,
modes: ["video-audio", "video-only", "audio-only", "picture"],
mirror: true,
facingMode: "user",
locale: {
strings: {
// Shown before a picture is taken when the `countdown` option is set.
smile: "Smile!",
// Used as the label for the button that takes a picture.
// This is not visibly rendered but is picked up by screen readers.
takePicture: "Take a picture",
// Used as the label for the button that starts a video recording.
// This is not visibly rendered but is picked up by screen readers.
startRecording: "Begin video recording",
// Used as the label for the button that stops a video recording.
// This is not visibly rendered but is picked up by screen readers.
stopRecording: "Stop video recording",
// Title on the “allow access” screen
allowAccessTitle: "Please allow access to your camera",
// Description on the “allow access” screen
allowAccessDescription:
"In order to take pictures or record video with your camera, please allow camera access for this site.",
},
},
})
.on("file-added", (file) => {
const { setFiles } = props;
setFiles(file);
})
}
componentWillUnmount() {
this.uppy.close();
}
render() {
this.uppy.on("complete", (result) => {
console.log(
"Upload complete! We’ve uploaded these files:",
result.successful
);
});
return (
<div>
<div>
<Dashboard
uppy={this.uppy}
plugins={["GoogleDrive", "Webcam", "Dropbox", "Instagram"]}
metaFields={[
{ id: "name", name: "Name", placeholder: "File name" },
]}
open={this.state.open}
target={document.body}
onRequestClose={() => this.setState({ open: false })}
/>
</div>
</div>
);
}
}
export default DashboardUppy;
And I use it like this nothing special:
import React, { useState } from "react";
import FileList from "./FileList";
import FileForm from "./FileForm";
import DashboardUppy from "./DashboardUppy";
import { Container, Grid } from "#material-ui/core";
const CreateContent = () => {
const [file, setItems] = useState();
const [show, showDashboardUppy] = useState(true);
return (
<Container maxWidth="lg">
{show ? (
<DashboardUppy showDashboardUppy={showDashboardUppy}/>
) : (
<Grid container spacing={3}>
<Grid item lg={4} md={6} xs={12}>
<FileList setItems={setItems} />
</Grid>
<Grid item lg={8} md={6} xs={12}>
<FileForm file={file} />
</Grid>
</Grid>
)}
</Container>
);
};
export default CreateContent;
Here is package.json
{
"name": "react-firestore-crud",
"version": "0.1.0",
"private": true,
"dependencies": {
"#uppy/core": "1.0.2",
"#uppy/dropbox": "latest",
"#uppy/form": "^1.3.23",
"#uppy/google-drive": "1.0.2",
"#uppy/instagram": "1.0.2",
"#uppy/react": "^1.0.2",
"#uppy/status-bar": "latest",
"#uppy/tus": "1.0.2",
"#uppy/webcam": "latest",
"#uppy/xhr-upload": "^1.6.8",
"#material-ui/core": "^4.11.2",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.57",
"#material-ui/styles": "^4.11.2",
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.3.2",
"#testing-library/user-event": "^7.1.2",
"bootstrap": "^4.5.2",
"clsx": "^1.1.1",
"firebase": "^7.23.0",
"moment": "^2.29.1",
"prop-types": "^15.7.2",
"react": "^16.8.4",
"react-dom": "^16.8.4",
"react-perfect-scrollbar": "^1.5.8",
"react-router-dom": "^5.2.0",
"react-scripts": "^3.4.0",
"uuid": "^8.3.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I hade the wrong Uppy version in package.json hmmm

React: does not match the corresponding name on disk/ emotion

error:
./src/App.tsx
Cannot find file: 'emotion-react.browser.esm.js' does not match the corresponding name on disk: 'C:\Users\gabrielti\Documents\emasa-management\node_modules\#emotion\react\dist\Emasa-Management'.
I use a mono repo structure, which is as follows
packages / client
packages / server
Mono repo package.json:
{
"name": "xemasa_monorepo",
"version": "1.0.0",
"main": "index.js",
"repository": "https://github.com/sptGabriel/x-Management.git",
"private":true,
"workspaces":{
"packages": [
"packages/*"
]
},
"author": "Gabriel Costa Cerqueira <Gabrielcerqueira96#hotmail.com>",
"license": "MIT",
"devDependencies": {
"husky": "^4.3.0"
},
"husky": {
"hooks": {
"prepare-commit-msg": "exec < /dev/tty && git cz --hook || true",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
Client package.json:
{
"name": "#emasa_monorepo/client",
"version": "0.1.0",
"dependencies": {
"#emotion/babel-preset-css-prop": "^11.0.0",
"#emotion/react": "^11.1.2",
"#emotion/styled": "^11.0.0",
"#testing-library/jest-dom": "^5.11.4",
"#testing-library/react": "^11.1.0",
"#testing-library/user-event": "^12.1.10",
"#types/styled-system": "^5.1.10",
"axios": "^0.21.0",
"class-validator": "^0.12.2",
"history": "^5.0.0",
"jsonwebtoken": "^8.5.1",
"lodash.get": "^4.4.2",
"mobx": "^6.0.4",
"mobx-react-lite": "2.2.2",
"mobx-state-tree": "^4.0.2",
"polished": "^4.0.5",
"prop-types": "^15.7.2",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-hamburger-menu": "^1.2.1",
"react-icons": "^4.1.0",
"react-router-dom": "^6.0.0-beta.0",
"react-scripts": "4.0.1",
"react-spinners": "^0.9.0",
"styled-system": "^5.1.5",
"typescript": "^4.1.2",
"universal-cookie": "^4.0.4",
"web-vitals": "^0.2.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"type-check": "tsc --project tsconfig.json --pretty --noEmit",
"lint": "eslint --ext js,jsx,ts,tsx --fix",
"prettier-format": "prettier --config .prettierrc ./src/**/*.{ts,tsx} --write"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"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"
]
},
"devDependencies": {
"#babel/plugin-proposal-decorators": "^7.12.1",
"#types/jest": "^26.0.15",
"#types/lodash.get": "^4.4.6",
"#types/node": "^14.14.10",
"#types/react": "^17.0.0",
"#types/react-dom": "^17.0.0",
"#types/react-hamburger-menu": "^0.0.3",
"#types/styled-components": "^5.1.4",
"#types/universal-cookie": "^2.2.0",
"#typescript-eslint/eslint-plugin": "^4.9.0",
"#typescript-eslint/parser": "^4.9.0",
"eslint": "^7.14.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-config-prettier": "^6.15.0",
"eslint-import-resolver-typescript": "^2.3.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-prettier": "^3.1.4",
"eslint-plugin-react": "^7.21.5",
"eslint-plugin-react-hooks": "^4.2.0",
"lint-staged": "^10.5.2",
"prettier": "^2.2.1",
"typescript": "^4.1.2"
},
"babel": {
"plugins": [
"transform-decorators-legacy",
"transform-class-properties"
],
"presets": [
"react-app"
]
}
}
babelrc
{
"presets": [
"react-app",
"#babel/preset-env",
"#babel/preset-react",
{
"runtime": "automatic",
"importSource": "#emotion/react"
}
],
"plugins": [
"#emotion/babel-plugin",
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}
app.jsx:
import React from 'react'
import { observer } from 'mobx-react-lite'
import { ThemeProvider } from '#emotion/react'
import { useAppTheme } from './shared/utils/useAppTheme'
import GlobalReset from './shared/utils/cssReset'
const App: React.FC = observer(() => {
const { theme } = useAppTheme()
return (
<ThemeProvider theme={theme}>
<GlobalReset />
<div>a</div>
</ThemeProvider>
)
})
export default App
file: emotion-react.browser.esm.js exists on :
enter image description here
emotion-react.browser.esm.js code:
import { createElement, useContext, useRef, useLayoutEffect } from 'react';
import '#emotion/cache';
import { h as hasOwnProperty, E as Emotion, c as createEmotionProps, w as withEmotionCache, T as ThemeContext } from './emotion-element-4fbd89c5.browser.esm.js';
export { C as CacheProvider, T as ThemeContext, a as ThemeProvider, u as useTheme, w as withEmotionCache, b as withTheme } from './emotion-element-4fbd89c5.browser.esm.js';
import '#babel/runtime/helpers/extends';
import '#emotion/weak-memoize';
import 'hoist-non-react-statics';
import '../isolated-hoist-non-react-statics-do-not-use-this-in-your-code/dist/emotion-react-isolated-hoist-non-react-statics-do-not-use-this-in-your-code.browser.esm.js';
import { insertStyles, getRegisteredStyles } from '#emotion/utils';
import { serializeStyles } from '#emotion/serialize';
import { StyleSheet } from '#emotion/sheet';
var pkg = {
name: "#emotion/react",
version: "11.1.2",
main: "dist/emotion-react.cjs.js",
module: "dist/emotion-react.esm.js",
browser: {
"./dist/emotion-react.cjs.js": "./dist/emotion-react.browser.cjs.js",
"./dist/emotion-react.esm.js": "./dist/emotion-react.browser.esm.js"
},
types: "types/index.d.ts",
files: [
"src",
"dist",
"jsx-runtime",
"jsx-dev-runtime",
"isolated-hoist-non-react-statics-do-not-use-this-in-your-code",
"types/*.d.ts",
"macro.js",
"macro.d.ts",
"macro.js.flow"
],
sideEffects: false,
author: "mitchellhamilton <mitchell#mitchellhamilton.me>",
license: "MIT",
scripts: {
"test:typescript": "dtslint types"
},
dependencies: {
"#babel/runtime": "^7.7.2",
"#emotion/cache": "^11.0.0",
"#emotion/serialize": "^1.0.0",
"#emotion/sheet": "^1.0.1",
"#emotion/utils": "^1.0.0",
"#emotion/weak-memoize": "^0.2.5",
"hoist-non-react-statics": "^3.3.1"
},
peerDependencies: {
"#babel/core": "^7.0.0",
react: ">=16.8.0"
},
peerDependenciesMeta: {
"#babel/core": {
optional: true
},
"#types/react": {
optional: true
}
},
devDependencies: {
"#babel/core": "^7.7.2",
"#emotion/css": "11.0.0",
"#emotion/css-prettifier": "1.0.0",
"#emotion/server": "11.0.0",
"#emotion/styled": "11.0.0",
"#types/react": "^16.9.11",
dtslint: "^0.3.0",
"html-tag-names": "^1.1.2",
react: "16.14.0",
"svg-tag-names": "^1.1.1"
},
repository: "https://github.com/emotion-js/emotion/tree/master/packages/react",
publishConfig: {
access: "public"
},
"umd:main": "dist/emotion-react.umd.min.js",
preconstruct: {
entrypoints: [
"./index.js",
"./jsx-runtime.js",
"./jsx-dev-runtime.js",
"./isolated-hoist-non-react-statics-do-not-use-this-in-your-code.js"
],
umdName: "emotionReact"
}
};
var jsx = function jsx(type, props) {
var args = arguments;
if (props == null || !hasOwnProperty.call(props, 'css')) {
// $FlowFixMe
return createElement.apply(undefined, args);
}
var argsLength = args.length;
var createElementArgArray = new Array(argsLength);
createElementArgArray[0] = Emotion;
createElementArgArray[1] = createEmotionProps(type, props);
for (var i = 2; i < argsLength; i++) {
createElementArgArray[i] = args[i];
} // $FlowFixMe
return createElement.apply(null, createElementArgArray);
};
var warnedAboutCssPropForGlobal = false; // maintain place over rerenders.
// initial render from browser, insertBefore context.sheet.tags[0] or if a style hasn't been inserted there yet, appendChild
// initial client-side render from SSR, use place of hydrating tag
var Global = /* #__PURE__ */withEmotionCache(function (props, cache) {
if (process.env.NODE_ENV !== 'production' && !warnedAboutCssPropForGlobal && ( // check for className as well since the user is
// probably using the custom createElement which
// means it will be turned into a className prop
// $FlowFixMe I don't really want to add it to the type since it shouldn't be used
props.className || props.css)) {
console.error("It looks like you're using the css prop on Global, did you mean to use the styles prop instead?");
warnedAboutCssPropForGlobal = true;
}
var styles = props.styles;
var serialized = serializeStyles([styles], undefined, typeof styles === 'function' || Array.isArray(styles) ? useContext(ThemeContext) : undefined);
// but it is based on a constant that will never change at runtime
// it's effectively like having two implementations and switching them out
// so it's not actually breaking anything
var sheetRef = useRef();
useLayoutEffect(function () {
var key = cache.key + "-global";
var sheet = new StyleSheet({
key: key,
nonce: cache.sheet.nonce,
container: cache.sheet.container,
speedy: cache.sheet.isSpeedy
}); // $FlowFixMe
var node = document.querySelector("style[data-emotion=\"" + key + " " + serialized.name + "\"]");
if (cache.sheet.tags.length) {
sheet.before = cache.sheet.tags[0];
}
if (node !== null) {
sheet.hydrate([node]);
}
sheetRef.current = sheet;
return function () {
sheet.flush();
};
}, [cache]);
useLayoutEffect(function () {
if (serialized.next !== undefined) {
// insert keyframes
insertStyles(cache, serialized.next, true);
}
var sheet = sheetRef.current;
if (sheet.tags.length) {
// if this doesn't exist then it will be null so the style element will be appended
var element = sheet.tags[sheet.tags.length - 1].nextElementSibling;
sheet.before = element;
sheet.flush();
}
cache.insert("", serialized, sheet, false);
}, [cache, serialized.name]);
return null;
});
if (process.env.NODE_ENV !== 'production') {
Global.displayName = 'EmotionGlobal';
}
function css() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return serializeStyles(args);
}
var keyframes = function keyframes() {
var insertable = css.apply(void 0, arguments);
var name = "animation-" + insertable.name; // $FlowFixMe
return {
name: name,
styles: "#keyframes " + name + "{" + insertable.styles + "}",
anim: 1,
toString: function toString() {
return "_EMO_" + this.name + "_" + this.styles + "_EMO_";
}
};
};
var classnames = function classnames(args) {
var len = args.length;
var i = 0;
var cls = '';
for (; i < len; i++) {
var arg = args[i];
if (arg == null) continue;
var toAdd = void 0;
switch (typeof arg) {
case 'boolean':
break;
case 'object':
{
if (Array.isArray(arg)) {
toAdd = classnames(arg);
} else {
if (process.env.NODE_ENV !== 'production' && arg.styles !== undefined && arg.name !== undefined) {
console.error('You have passed styles created with `css` from `#emotion/react` package to the `cx`.\n' + '`cx` is meant to compose class names (strings) so you should convert those styles to a class name by passing them to the `css` received from <ClassNames/> component.');
}
toAdd = '';
for (var k in arg) {
if (arg[k] && k) {
toAdd && (toAdd += ' ');
toAdd += k;
}
}
}
break;
}
default:
{
toAdd = arg;
}
}
if (toAdd) {
cls && (cls += ' ');
cls += toAdd;
}
}
return cls;
};
function merge(registered, css, className) {
var registeredStyles = [];
var rawClassName = getRegisteredStyles(registered, registeredStyles, className);
if (registeredStyles.length < 2) {
return className;
}
return rawClassName + css(registeredStyles);
}
var ClassNames = /* #__PURE__ */withEmotionCache(function (props, cache) {
var hasRendered = false;
var css = function css() {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('css can only be used during render');
}
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var serialized = serializeStyles(args, cache.registered);
{
insertStyles(cache, serialized, false);
}
return cache.key + "-" + serialized.name;
};
var cx = function cx() {
if (hasRendered && process.env.NODE_ENV !== 'production') {
throw new Error('cx can only be used during render');
}
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return merge(cache.registered, css, classnames(args));
};
var content = {
css: css,
cx: cx,
theme: useContext(ThemeContext)
};
var ele = props.children(content);
hasRendered = true;
return ele;
});
if (process.env.NODE_ENV !== 'production') {
ClassNames.displayName = 'EmotionClassNames';
}
if (process.env.NODE_ENV !== 'production') {
var isBrowser = "object" !== 'undefined'; // #1727 for some reason Jest evaluates modules twice if some consuming module gets mocked with jest.mock
var isJest = typeof jest !== 'undefined';
if (isBrowser && !isJest) {
var globalContext = isBrowser ? window : global;
var globalKey = "__EMOTION_REACT_" + pkg.version.split('.')[0] + "__";
if (globalContext[globalKey]) {
console.warn('You are loading #emotion/react when it is already loaded. Running ' + 'multiple instances may cause problems. This can happen if multiple ' + 'versions are used, or if multiple builds of the same version are ' + 'used.');
}
globalContext[globalKey] = true;
}
}
export { ClassNames, Global, jsx as createElement, css, jsx, keyframes };
I already searched and found nothing about it, I don't know what's going on

GatsbyJS + Netlify + MDX loader issue

I am making a style guide with a CMS and running into a few issues.
This is my webpack config
exports.onCreateWebpackConfig = ({ actions }) => {
actions.setWebpackConfig({
plugins: [
new WebpackNotifierPlugin({
skipFirstNotification: true,
}),
],
resolve: {
// Enable absolute import paths
modules: [path.resolve(__dirname, 'src'), 'node_modules'],
extensions: ['.js', '.jsx', '.json', '.tsx'],
},
})
}
This is my package.json
"#babel/core": "^7.2.2",
"#material-ui/core": "^4.9.1",
"#material-ui/icons": "^4.9.1",
"#mdx-js/mdx": "^0.16.8",
"#mdx-js/tag": "^0.16.6",
"#reach/router": "^1.2.1",
"#typescript-eslint/parser": "^2.19.0",
"d3-ease": "^1.0.5",
"docz-utils": "^0.13.6",
"gatsby": "^2.0.76",
"gatsby-image": "^2.0.20",
"gatsby-link": "^2.2.29",
"gatsby-mdx": "^0.3.4",
"gatsby-plugin-catch-links": "^2.0.9",
"gatsby-plugin-manifest": "^2.0.9",
"gatsby-plugin-mdx": "^1.0.67",
"gatsby-plugin-netlify-cms": "4.1.40",
"gatsby-plugin-offline": "^2.0.16",
"gatsby-plugin-sharp": "^2.0.14",
"gatsby-react-router-scroll": "^2.1.21",
"gatsby-source-filesystem": "^2.0.16",
"gatsby-transformer-sharp": "^2.1.8",
"hast-util-to-string": "^1.0.1",
"jss": "^10.0.4",
"jsx-to-string": "^1.4.0",
"lodash": "^4.17.11",
"marked": "^0.6.0",
"netlify-cms-app": "2.9.1",
"netlify-cms-widget-mdx": "^0.4.3",
"netlify-identity-widget": "^1.5.6",
"prismjs": "^1.15.0",
"prop-types": "^15.6.2",
"react": "^16.8.0",
"react-dom": "^16.8.0",
"react-head": "^3.0.2",
"react-highlight": "^0.12.0",
"react-powerplug": "^1.0.0",
"styled-system": "^3.2.1",
"unstated": "^2.1.1",
"write": "^1.0.3"
This is my component:
interface IButtons {
children: React.ReactElement;
}
const useStyles = makeStyles({
root: {
},
button: {
display: 'flex',
justifyContent: 'space-between' as 'space-between',
padding: `16px 8px`,
paddingRight: '50px',
background: `#F7F9FE`,
position: 'relative' as 'relative'
},
expand: {
position: 'absolute' as 'absolute',
top: 0,
right: 0,
cursor: 'pointer'
},
code: {
padding: `16px`,
fontSize: `14px`
}
});
const Buttons = (props: IButtons) => {
const classes = useStyles();
const [isCodeOpen, setCode] = useState(false)
const children = React.Children.toArray(props.children)
const stringChildren = useMemo(() => {
let stringed: string[] | string = []
for (let i = 0; i < React.Children.count(children); i++) {
stringed
.push(jsxToString(props.children[i])
.replace('WithStyles(ForwardRef(Button))', 'Button')
.replace('/WithStyles(ForwardRef(Button))', '/Button'))
}
return stringed.join("\n\n")
}, [props.children])
return (
<section className={classes.root}>
<div className={classes.button}>
<CodeIcon className={classes.expand} fontSize='small' onClick={() => setCode(!isCodeOpen)}></CodeIcon>
{props.children}
</div>
{isCodeOpen &&
<Highlight language="javascript" className={classes.code}>
{stringChildren}
</Highlight>}
</section>
)
}
And these are my UI components
export const UIComponents = {
...UI,
DeleteIcon,
Buttons,
// TODO: include additional custom components here, eg:
Janky: props => <UI.TextField {...props} placeholder={'janky'} />
}
And my query
{
resolve: "gatsby-mdx",
options: {
extensions: [".mdx", ".md"],
defaultLayouts: {
default: require.resolve("./src/components/Layout/index.tsx"),
},
globalScope: `
import { UIComponents } from 'Theme'
export default {
...UIComponents
}
`,
// mdPlugins: [],
// gatsbyRemarkPlugins: [{}],
},
},
The first issue I am encountering when starting the app is I get this error message. I am not sure what loaders I need to put.
Module parse failed: The keyword 'interface' is reserved (8:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import jsxToString from 'jsx-to-string';
|
> interface IButtons {
| children: React.ReactElement;
| }
# ./src/Theme.jsx 32:0-43 123:11-18
# ./src/cms/cms.jsx
# multi ./node_modules/gatsby-plugin-netlify-cms/cms.js ./src/cms/cms
The second issue is that in my netlify cms preview I get:
Invalid MDX:
ReferenceError: Buttons is not defined
Even though in the App itself the Buttons component renders, in the preview it does not.
Gatsby does not ship with Typescript support out of the box, but you can add it easily with the gatsby-plugin-typescript plugin.
Install
npm install gatsby-plugin-typescript
How to use
Include the plugin in your gatsby-config.js file.
Write your components in TSX or TypeScript.
You’re good to go.
gatsby-config.js
module.exports = {
// ...,
plugins: [`gatsby-plugin-typescript`],
}

FlatList not able to Render items

On Fetching the Json data from remote url and while trying to render it via FlatList Component ,I am constantly getting Red-Screen with this error "incompatible receiver map required" .
I strongly guess it is related to android.
Json Response is coming properly as seen in react-logger.
I tried adding core-js : 2.5.2 in "resolutions" in package.json but still did not work.
HomeScreen.js
import React, { Component } from "react";
import {
Text,
View,
FlatList,
ActivityIndicator,
Platform
} from "react-native";
import { Button } from "native-base";
import { connect } from "react-redux";
import firebase from "react-native-firebase";
import { onSignOut } from "../Actions/AuthActions";
import { stringify } from "qs";
class HomeScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
};
}
static navigationOptions = {
header: null
};
componentDidMount() {
// Checking user Auth State
this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
this.props.navigation.navigate(user ? "App" : "Auth");
});
// Fetching the list of workers from Remote Url
return fetch("https://api.myjson.com/bins/xyz")
.then(response => response.json())
.then(responseJson => {
this.setState(
{
isLoading: false,
dataSource: responseJson.workers
},
function() {
// In this block you can do something with new state.
}
);
})
.catch(error => {
console.error(error);
});
}
componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
}
render() {
// First Loadf the activity indicator till the json data is not fetched
if (this.state.isLoading) {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<ActivityIndicator />
</View>
);
}
console.log(JSON.stringify(this.state.dataSource));
return (
<View style={styles.container}>
<FlatList>
data = {this.state.dataSource}
renderItem=
{({ item }) => <Text>{item.name}</Text>}
keyExtractor={(item, index) => index}
</FlatList>
</View>
);
}
}
const styles = {
container: {
flex: 1,
alignItems: "center",
alignContent: "center",
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "center"
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44
}
};
package.json
{
"scripts": {
"start": "react-native start",
"android": "react-native run-android",
"ios": "react-native run-ios"
},
"dependencies": {
"#babel/runtime": "^7.4.4",
"firebase": "^5.11.1",
"isomorphic-fetch": "^2.2.1",
"native-base": "^2.12.1",
"prop-types": "^15.7.2",
"react": "^16.8.6",
"react-native": "0.57.5",
"react-native-elements": "^1.1.0",
"react-native-firebase": "^5.3.1",
"react-native-gesture-handler": "^1.1.0",
"react-native-google-places-autocomplete": "^1.3.9",
"react-native-otp-inputs": "^2.0.1",
"react-native-phone-input": "^0.2.1",
"react-navigation": "^3.9.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"redux-immutable-state-invariant": "^2.1.0",
"redux-thunk": "^2.3.0"
},
"devDependencies": {
"babel-polyfill": "^6.26.0",
"babel-preset-expo": "^5.0.0",
"eslint-plugin-react-hooks": "^1.6.0",
"expo": "^32.0.6"
},
"resolutions": {
"core-js": "2.5.2"
},
"private": true
}
Error Should not come and items should be rendered accordingly.
Check your response first. Is it the right array like as [{name: 'a'}, {name: 'b"}]?
// Fetching the list of workers from Remote Url
return fetch("https://api.myjson.com/bins/xyz")
.then(response => response.json())
.then(responseJson => {
console.log(responseJson); // Check your response
this.setState(
{
isLoading: false,
dataSource: responseJson.workers
},
function() {
// In this block you can do something with new state.
}
);
})
.catch(error => {
console.error(error);
});
}
Update
You used flatlist to wrong way.
<FlatList>
data = {this.state.dataSource}
renderItem=
{({ item }) => <Text>{item.name}</Text>}
keyExtractor={(item, index) => index}
</FlatList>
need to change below
<FlatList
data={this.state.datasource}
renderItem={...}
/>

Can't seem to get three.js to rotate correctly when using react and three.js

I am using react on typescript, and trying to figure out how three.js works but have stumbled on a few problems regarding camera rotation, and in general camera movement
OnComponentDidMount loads my fake data and begins to draw. I manage to draw the image (not correctly but i draw it none the less)
I have tried to add rotations by using OrbitControls, but this has been an issue, as the image i render, cant be interacted with: I cant zoom rotate or anything else.
A secondary issue is that the way i am rendering in the component feels very "hacky", and is not how i would like it to render.
A lot of the work is inspired from "https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_normals.html" - Currently i am simple trying to get react and three.js working together in a react environment, and not very focused on the actual data that is rendered.
import React from 'react';
import * as THREE from 'three';
import { OrbitControls } from 'three-orbitcontrols-ts';
export interface IMapperState {
canvasReady: boolean;
}
export default class Drawer extends React.Component<{}, IMapperState> {
private map: THREE.WebGLRenderer;
private camera: THREE.PerspectiveCamera;
private scene: THREE.Scene;
constructor(props: any) {
super(props);
this.map = new THREE.WebGLRenderer({ antialias: true });
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
this.state = { canvasReady: false }
}
private draw = (data: any) => {
this.scene.background = new THREE.Color(0xcce0ff);
this.camera.position.set(10, 10, 30);
this.map.setSize(window.innerWidth / 2, window.innerHeight / 2);
data.box.forEach(coord => {
const geometry = new THREE.BoxGeometry(coord.x, coord.z, coord.y)
const wallImage = new THREE.MeshBasicMaterial({ opacity: 0.1, color: "red" })
const wall = new THREE.Mesh(geometry, wallImage);
wall.position.setX(coord.x);
wall.position.setY(coord.y);
this.scene.add(wall)
});
const controls = new OrbitControls(this.camera);
this.map.render(this.scene, this.camera);
this.map.gammaInput = true;
this.map.gammaOutput = true;
this.map.shadowMap.enabled = true;
window.addEventListener("resize", this.onWindowResize, false);
this.setState({ canvasReady: true })
}
private onWindowResize = () => {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.map.setSize(window.innerWidth / 2, window.innerHeight / 2);
}
public componentDidMount() {
const mockData = {
box: [
{ x: 10, y: 30, z: 100 }
]
};
this.draw(mockData);
}
render(): JSX.Element {
if (this.state.canvasReady) {
if (document.getElementById("threeJsTest")) {
var el: HTMLElement | null = document.getElementById("threeJsTest");
if (el) {
el.appendChild(this.map.domElement);
}
}
}
return (
<div id="threeJsTest" />
);
}
}
Package.json
{
"name": "threejsreactdemo",
"version": "0.1.0",
"private": true,
"dependencies": {
"#types/jest": "23.3.10",
"#types/node": "10.12.18",
"#types/react": "16.7.17",
"#types/react-dom": "16.0.11",
"#types/three": "^0.93.13",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-scripts": "2.1.1",
"three": "^0.99.0",
"three-orbitcontrols-ts": "^0.1.2",
"typescript": "3.2.2"
},
"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": {}
}
Actual results: I cant interact with the image and my render method is not very pretty.
Wanted result: Hopefully i cleaner render method - and the ability to zoom / rotate the rendered image - in react: typescript

Resources