FlatList not able to Render items - reactjs

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

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

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

Reactjs returns error unexpected token with dropdown menu records

I know this question may have been asked but am just frustrated. Reactjs marks = at the line of code below as unexpected token error
handleChange1 = {(selectedOption) => {
All the required dependency has been installed.
below is the entire code
import React, { Component } from 'react';
import { render } from 'react-dom';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import Hello from './Hello';
import Select from 'react-select'
//import './style.css';
import 'react-select/dist/react-select.css';
class Plans extends Component {
constructor() {
super();
this.state = {
name: 'React',
selectedOption: {},
selectedOption2: {}
};
}
handleChange1 = {(selectedOption) => {
this.setState({selectedOption});
}
};
handleChange2 = (selectedOption) => {
this.setState({selectedOption2: selectedOption})
}
render() {
const options1 = [
{value: 'one', label: 'One'},
{value: 'two', label: 'Two'}
];
const options2 = [
{value: 'one-a', label: 'One A', link: 'one'},
{value: 'one-b', label: 'One B', link: 'one'},
{value: 'two-a', label: 'Two A', link: 'two'},
{value: 'two-b', label: 'Two B', link: 'two'}
];
const filteredOptions = options2.filter((o) => o.link === this.state.selectedOption.value)
return (
<div>
<p>Select one first</p>
<Select
name="form-field-name"
value={this.state.selectedOption.value}
onChange={this.handleChange1}
options={options1}
/>
<p>Then the other</p>
<Select
name="form-field-name"
value={this.state.selectedOption2.value}
onChange={this.handleChange2}
options={filteredOptions}
/>
</div>
);
}
}
//render(<Plans />, document.getElementById('app'));
function mapStateToProps(state) {
}
const connectedPlans = connect(mapStateToProps)(Plans);
export { connectedPlans as Plans };
Here is my package.json
{
"name": "example",
"version": "1.0.0",
"repository": {
"type": "git",
"url": ""
},
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --open"
},
"dependencies": {
"history": "^4.6.3",
"node-sass": "^4.9.4",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "^5.0.5",
"react-router-dom": "^4.1.2",
"react-select": "^2.1.1",
"react-toastify": "^4.4.0",
"redux": "^3.7.2",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.2.0"
},
"devDependencies": {
"babel-core": "^6.21.0",
"babel-loader": "^7.1.2",
"babel-preset-es2015": "^6.18.0",
"babel-preset-react": "^6.16.0",
"babel-preset-stage-3": "^6.24.1",
"css-loader": "^1.0.1",
"html-webpack-plugin": "^2.26.0",
"path": "^0.12.7",
"sass-loader": "^7.1.0",
"style-loader": "^0.23.1",
"webpack": "^3.6.0",
"webpack-dev-server": "^2.8.2"
}
}
Updates
App.jsx
import React from 'react';
import { Router, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import { history } from '../_helpers';
import { alertActions } from '../_actions';
import { PrivateRoute } from '../_components';
import { Plans } from '../Plans';
class App extends React.Component {
constructor(props) {
super(props);
const { dispatch } = this.props;
history.listen((location, action) => {
// clear alert on location change
dispatch(alertActions.clear());
});
}
render() {
const { alert } = this.props;
return (
<div className="jumbotron">
<div className="container">
<div className="col-sm-8 col-sm-offset-2">
{alert.message &&
<div className={`alert ${alert.type}`}>{alert.message}</div>
}
<Router history={history}>
<div>
<Route path="/plans" component={Plans} />
</div>
</Router>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { alert } = state;
return {
alert
};
}
const connectedApp = connect(mapStateToProps)(App);
export { connectedApp as App };
How I solve the problem. First I implemented the solution powered by Dacre in the comments above. I then discovered that react-select.css' files is not in the node_modules so I re-install it again so as to enable me to import it..
I added this line of code below
render(<Plans />, document.getElementById('app'));
and then remove the code below
function mapStateToProps(state) {
}
const connectedPlans = connect(mapStateToProps)(Plans);
export { connectedPlans as Plans };

React Navigation V2 does not display bar, React Native

I recently started to learn React-Native and I was trying to implement React-Navigation V2 in one of my project but it does not seem to work. The project also uses Redux and other dependencies along with the core installed by Expo.
This is the code for my Router component that manages the Navigation:
import { createStackNavigator } from 'react-navigation';
import Movie from './Movie';
import Home from './Home';
const RoutRouter = createStackNavigator({
Movie : {
screen : Movie
},
Home : {
screen : Home
}
}, {
initialRouteName : 'Home'
});
export default RoutRouter;
Home Component
import React, { Component } from 'react';
import { View, Text, Button } from 'react-native';
class Home extends Component {
render() {
console.log('Home screen');
return (
<View>
<Text>HOME</Text>
</View>
);
}
}
export default Home;
Movie Component
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { View, Text, Button } from 'react-native';
import { apiRequest } from '../actions';
import { MOVIE } from '../constants';
class Movie extends Component {
//api request to retrieve data
getData = () => {
console.log('Button works!');
}
render() {
console.log('Movie screen');
return (
<View>
<Text>MOVIE</Text>
<Button title = 'Get Movie' onPress = {()=> {this.getData()}} />
</View>
);
}
}
const mapStateToProps = (state) => {
return{
state : state
}
}
export default connect(mapStateToProps, {apiRequest})(Movie);
Main Component
import React from 'react';
import { Provider } from 'react-redux';
import { StyleSheet, Text, View, Button, SafeAreaView } from 'react-native';
import store from './src/store';
import RootRouter from './src/routes/Router';
import { Constants } from 'expo';
console.ignoredYellowBox = ['Remote debugger'];
export default class App extends React.Component {
render() {
console.log('stae');
return (
<Provider store = { store }>
<SafeAreaView>
<View style={styles.container}>
<RootRouter />
</View>
</SafeAreaView>
</Provider>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: Constants.statusBarHeight,
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
and this is my package.json
{
"name": "m",
"version": "0.1.0",
"private": true,
"devDependencies": {
"jest-expo": "~27.0.0",
"react-native-scripts": "1.14.0",
"react-test-renderer": "16.3.1"
},
"main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
"scripts": {
"start": "react-native-scripts start",
"eject": "react-native-scripts eject",
"android": "react-native-scripts android",
"ios": "react-native-scripts ios",
"test": "jest"
},
"jest": {
"preset": "jest-expo"
},
"dependencies": {
"axios": "^0.18.0",
"expo": "^27.0.1",
"react": "16.3.1",
"react-native": "~0.55.2",
"react-navigation": "^2.11.2",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"redux-thunk": "^2.3.0"
}
}
At first I thought I was getting error but then when I logged the screen out I noticed that on the debugger the screen message is shown but the screen is blank.
Any idea what am I missing?

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