GatsbyJS + Netlify + MDX loader issue - reactjs

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`],
}

Related

Tailwind not implementing color additions

I'm trying to use Tailwind in my project and I can get different styles to work, e.g. bold, round, flex, etc. However, none of the colors are coming through and I'm not sure why. I'm eventually hoping to use custom colors but that's not working either.
postcss.config.js
module.exports = {
plugins: [require('tailwindcss'), require('autoprefixer')]
};
tailwind.config.js
const colors = require('tailwindcss/colors')
module.exports = {
content: [
'./pages/**/*.{html,js}',
'./components/**/*.{html,js}',
'./index.html'
],
theme: {
colors: {
white: '#ffffff',
blue: {
medium: '#005c98'
},
black: {
light: '#005c98',
faded: '#00000059'
},
gray: {
base: '#616161',
background: '#fafafa',
primary: '#dbdbdb'
}
}
}
};
Styles I'm trying to apply to my button:
className={`bg-blue-500 text-black w-full rounded h-8 font-bold
${isInvalid && 'opacity-50'}`}
package.json dev dependencies
"devDependencies": {
"autoprefixer": "^10.4.8",
"eslint": "^6.3.0",
"eslint-loader": "^3.0.0",
"npm-run-all": "^4.1.5",
"postcss-cli": "^10.0.0",
"prop-types": "^15.8.1",
"tailwindcss": "^3.1.7"
}
You are overriding all of the default colors in your tailwind.config.css. If you want to keep the defaults and add a few new colors, you should use the extend property.
module.exports = {
content: [
"./pages/**/*.{html,js}",
"./components/**/*.{html,js}",
"./index.html",
],
theme: {
extend: {
colors: {
white: "#ffffff",
blue: {
medium: "#005c98",
},
black: {
light: "#005c98",
faded: "#00000059",
},
gray: {
base: "#616161",
background: "#fafafa",
primary: "#dbdbdb",
},
},
},
},
};

Storybook + MUI5 + Nextjs - theme issue?

I finally managed to get SB working with mui4, but after upgrading the mui5, i can't get it going.
installed with Npx sb init —builder webpack5
updated sb main.js as per
Complained that "compressible' module couldn't be found so installed that.
Ran npm i core-js#3.8.2 as gives out about es-weak-map + others not found.
Added web pack 5 as a dev dependency npm install webpack#5 --save-dev
npx sb#next upgrade --prerelease.
plus literally every other suggestion i came across online, which you can see in these files (leaving some comments in so you can see what else i tried in some cases)
.storybook>main.js
const path = require('path');
const toPath = filePath => path.join(process.cwd(), filePath);
module.exports = {
stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.#(js|jsx|ts|tsx)'],
addons: [
'#storybook/addon-links',
'#storybook/addon-essentials',
'#storybook/addon-interactions',
// 'storybook-addon-designs',
// 'storybook-anima',
// '#storybook/addon-actions',
{
name: '#storybook/addon-docs',
options: {
configureJSX: true,
babelOptions: {},
sourceLoaderOptions: null,
transcludeMarkdown: true,
},
},
'#storybook/builder-webpack5',
],
framework: '#storybook/react',
core: {
// builder: '#storybook/builder-webpack5',
builder: 'webpack5',
},
typescript: { reactDocgen: false },
features: {
emotionAlias: false,
modernInlineRendering: true,
},
webpackFinal: async (config, { configType }) => {
config.resolve.modules = [path.resolve(__dirname, '..', '.'), 'node_modules'];
config.resolve.alias = {
...config.resolve.alias,
'#emotion/core': toPath('node_modules/#emotion/react'),
'emotion-theming': toPath('node_modules/#emotion/react'),
// 'core-js/modules/es.weak-map.js': toPath('core-js/modules/es6.weak-map.js'),
};
return config;
// return {
// ...config,
// resolve: {
// ...config.resolve,
// alias: {
// ...config.resolve.alias,
// '#emotion/core': toPath('node_modules/#emotion/react'),
// 'emotion-theming': toPath('node_modules/#emotion/react'),
// },
// },
// };
},
};
.package.json
{ "dependencies": {
"#auth0/nextjs-auth0": "^1.7.0",
"#emotion/react": "^11.8.2",
"#emotion/styled": "^11.8.1",
"#material-ui/core": "^4.12.0",
"#material-ui/icons": "^4.11.2",
"#material-ui/lab": "^4.0.0-alpha.60",
"#mui/icons-material": "^5.5.1",
"#mui/lab": "^5.0.0-alpha.75",
"#mui/material": "^5.5.3",
"#mui/styles": "^5.5.3",
"core-js": "^3.8.2",
"cors": "^2.8.5",
"next": "^12.1.4",
"react": "latest",
},
"devDependencies": {
"#storybook/addon-actions": "^6.5.0-alpha.59",
"#storybook/addon-essentials": "^6.5.0-alpha.59",
"#storybook/addon-interactions": "^6.5.0-alpha.59",
"#storybook/addon-links": "^6.5.0-alpha.59",
"#storybook/builder-webpack5": "^6.5.0-alpha.59",
"#storybook/manager-webpack5": "^6.5.0-alpha.59",
"#storybook/node-logger": "^6.5.0-alpha.59",
"#storybook/preset-create-react-app": "^4.1.0",
"#storybook/react": "^6.5.0-alpha.59",
"#storybook/testing-library": "^0.0.9",
"#svgr/webpack": "^6.2.1",
"compressible": "^2.0.18",
"webpack": "^5.72.0"
},
"eslintConfig": {
"overrides": [
{"files": ["**/*.stories.*"],
"rules": {"import/no-anonymous-default-export": "off"}
}]
},
"resolutions": {"#storybook/{app}/webpack": "^5"}
}
my Story
// import { ThemeProvider } from '#mui/styles';
import { ThemeProvider as MUIThemeProvider, createTheme } from '#mui/material/styles';
import { ThemeProvider } from 'emotion-theming';
import React from 'react';
//import theme from 'src/themes/theme.js';
// import DuplicateComponent from 'src/components/helpers/DuplicateComponent';
// import TickerTicket from 'src/components/modules/dashboard/TickerTicket';
import DataLanes from '.';
export default {
title: 'components/common/dataDisplay/DataLanes',
component: DataLanes,
};
export const Bare = () => (
// <MUIThemeProvider theme={theme}>
// <ThemeProvider theme={theme}>
<DataLanes borderBottom>
<div>1</div>
<div>2</div>
<div>3</div>
</DataLanes>
// </ThemeProvider>
// </MUIThemeProvider>
);
My Component
import { Box } from '#mui/material';
import clsx from 'clsx';
import React from 'react';
import PropTypes from 'prop-types';
import useStyles from './styles';
export default function DataLanes(props) {
const classes = useStyles();
const { borderBottom, borderTop, className, children, ...others } = props;
return (
<Box
className={clsx(classes.dataLanes, className, {
borderBottom: borderBottom,
borderTop: borderTop,
})}
{...others}
>
{children}
</Box>
);
}
its styling
import makeStyles from '#mui/styles/makeStyles';
const useStyles = makeStyles(theme => ({
dataLanes: {
width: '100%',
background: theme.palette.background.paper,
display: 'flex',
paddingTop: theme.spacing(1),
paddingBottom: theme.spacing(1),
overflowY: 'auto',
'& > * ': {
flexGrow: 1,
borderRight: `1px solid ${theme.palette.grey[300]}`,
},
'&.borderBottom': {
borderBottom: `1px solid ${theme.palette.grey[300]}`,
},
'&.borderTop': {
borderTop: `1px solid ${theme.palette.grey[300]}`,
},
},
}));
export default useStyles;
Any thoughts? It seems like it's the background: theme.palette.background.paper,
in the style.js.
For similar issues I encountered with MUI and storybook this change at the preview.js in the .storybook folder solved it.
.storybook>preview.js
import React from 'react';
import { addDecorator } from '#storybook/react';
import { ThemeProvider } from '#mui/material/styles';
import { theme } from '../src/Theme'; //. Please replace the path for the theme with yours.
export const parameters = {
actions: { argTypesRegex: '^on[A-Z].*' },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
addDecorator(story => <ThemeProvider theme={theme}>{story()}</ThemeProvider>);

gatsby-source-graphql only absolute urls are supported

I'm integrating graphQL into my gatsby site. I am getting an error that says "only absolute urls are supported" and then points to some code in the node-fetch library. There isn't an obvious path to how I'm getting that code to execute though, so I'm not sure what the source of my issue is. I have done several days worth of searching, and while I have found several threads about this error, it's never been in the context of gatsby-source-graphql. Any help would be appreciated.
package.json
{
.
.
.
"dependencies": {
"ajv": "^6.9.2",
"core-js": "^2.6.5",
"fullcalendar": "^3.9.0",
"fullcalendar-reactwrapper": "^1.0.7",
"gatsby": "^2.12.0",
"gatsby-cli": "^2.7.20",
"gatsby-plugin-manifest": "^2.0.2",
"gatsby-plugin-netlify-cms": "^4.0.1",
"gatsby-plugin-offline": "^2.0.5",
"gatsby-plugin-react-helmet": "^3.0.0",
"gatsby-plugin-sass": "^2.0.1",
"gatsby-source-filesystem": "^2.1.6",
"gatsby-source-graphql": "^2.1.3",
"gatsby-transformer-remark": "^2.6.9",
"graphql": "^14.1.1",
"jquery": "^3.3.1",
"moment": "^2.22.2",
"netlify-cms-app": "^2.9.1",
"node-sass": "^4.9.3",
"react": "^16.5.1",
"react-calendar": "^2.17.5",
"react-dom": "^16.6.3",
"react-helmet": "^5.2.0",
"react-native-calendars": "^1.21.0"
},
.
.
.
"devDependencies": {
"#material-ui/core": "^3.9.2",
"#material-ui/icons": "^3.0.2",
"material-icons-react": "^1.0.4",
"prettier": "^1.14.2",
"react-tooltip": "^3.9.2",
"surge": "^0.20.1"
},
.
.
.
}
UpcomingScheduleChanges.js
import React from 'react';
import { StaticQuery, graphql } from 'gatsby';
import Cancellations from './Cancellations';
class UpcomingScheduleChanges extends React.Component {
render() {
console.log(this.props.cancellations)
return (
<div className="col-6">
<header className="major">
<h2>Upcoming Schedule Changes</h2>
</header>
{this.props.cancellations ? (
<Cancellations cancellations={this.props.cancellations}></Cancellations>
) : (
<p>There are no upcomimng schedule changes!</p>
)}
</div>
)
}
}
export default () => (
<StaticQuery
query={graphql`
query ScheduleChanges {
allMarkdownRemark {
edges {
node {
frontmatter {
cancellation {
date(formatString: "MMMM DD")
day
location
type
}
}
}
}
}
}
`}
render={(data) => <UpcomingScheduleChanges cancellations={data.allMarkdownRemark.edges[0].node.frontmatter.cancellation} />}
/>
);
index.js
import React from "react";
import Helmet from "react-helmet";
import Layout from "../components/layout";
import ReactTooltip from "react-tooltip";
import ContactForm from "../components/ContactForm";
import Schedule from '../components/Schedule';
import Welcome from "../components/Welcome";
import Administrators from "../components/Administrators";
import MailingList from "../components/MailingList";
class Homepage extends React.Component {
handleClick(url) {
window.open(url, "_blank");
}
render() {
const siteTitle = "...";
return (
<Layout>
<Helmet title={siteTitle}>
<script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></script>
</Helmet>
<Welcome></Welcome>
<Schedule></Schedule>
<Administrators></Administrators>
<MailingList></MailingList>
<ContactForm></ContactForm>
<ReactTooltip />
<script>
{`if (window.netlifyIdentity) {
window.netlifyIdentity.on("init", user => {
if (!user) {
window.netlifyIdentity.on("login", () => {
document.location.href = "/admin/";
});
}
});
}`}
</script>
</Layout>
);
}
}
export default Homepage;
gatsby-config.js
module.exports = {
siteMetadata: {
title: "...",
author: "...",
description: "..."
},
plugins: [
'gatsby-plugin-react-helmet',
{
resolve: `gatsby-plugin-manifest`,
options: {
name: '...',
short_name: '...',
start_url: '/',
background_color: '#FFFFFF',
theme_color: '#FFFFFF',
display: 'minimal-ui',
icon: 'src/assets/images/banner_small.png', // This path is relative to the root of the site.
},
},
'gatsby-plugin-sass',
'gatsby-transformer-remark',
{
resolve: 'gatsby-source-filesystem',
options: {
path: `${__dirname}/static/content`,
name: 'content'
}
},
{
resolve: "gatsby-source-graphql",
options: {
typeName: "cancellations",
fieldName: "cancellations",
url: `${__dirname}/static/content/cancellations.md`
}
},
'gatsby-plugin-offline',
'gatsby-plugin-netlify-cms'
],
}
config.yml
backend:
name: git-gateway
branch: master #branch to update (optional; defaults to master)
publish_mode: editorial_workflow #allows for a drafting, reviewing, and approving process for changes
media_folder: "src/assets/images/uploads"
public_folder: "/images"
#collections
collections:
- label: "Upcoming Schedule Changes"
name: "upcoming schedule changes"
files:
- label: "Cancellations"
name: "cancellations"
file: "static/content/cancellations.md"
fields:
- label: "Cancellations"
name: "cancellations"
create: true
widget: "list"
fields:
- {label: "Date", name: "date", widget: "date"}
- {label: "Day", name: "day", widget: "select", options: ["Thursday", "Friday", "Sunday"]}
- {label: "Location", name: "location", widget: "select", options: ["Location1", "Location2", "Location3"]}
- {label: "Type", name: "type", widget: "select", options: ["Cancelled", "Delayed", "Relocated"]}

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={...}
/>

babel decorator plugin not working

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"]
}

Resources