I'm trying to implement react-keydown which can be found here: https://github.com/glortho/react-keydown using the following code example:
import React from 'react';
import keydown, { Keys } from 'react-keydown';
class MethodDecoratorExample extends React.Component {
constructor( props ) {
super( props );
this.state = {
hello: false
};
}
#keydown( 'enter' )
toggleHello() {
this.setState( { hello: !this.state.hello } );
}
render() {
return (
<div>
<h3>Method Decorator Example</h3>
<div>Press the <strong>enter</strong> key to toggle hello.</div>
{ this.state.hello &&
<h1>Enter is key code {Keys.enter}!</h1>
}
<div>And click again outside box to see scoping.</div>
</div>
);
}
}
When I try this I get an unexpected token error on the #. I have no clue how to solve this.
What am I missing?
Thanks
Babel 6 no longer supports ES decorator syntax out of the box so you need to install the babel-plugin-transform-decorators-legacy plugin.
Install babel-plugin-transform-decorators-legacy
npm install --save-dev babel-plugin-transform-decorators-legacy
Add the plugin in your .babelrc
{
"plugins": [
"transform-decorators-legacy"
]
}
or
add the loader directly in your webpack.config.js
{
test: /\.jsx?$/,
loader: 'babel',
query: {
cacheDirectory: true,
plugins: ['transform-decorators-legacy' ]
}
}
I found the answer here: How do I get decorators working with babel & webpack?
Thanks to #cbll for mentioning decorators, because I did not know that that is the correct term. Helped me with searching for solutions
Related
I'm trying to use react-image-annotate but it's giving me this issue when I first try to set it up.
And here's how I'm using it:
import React from 'react'
import ReactImageAnnotate from 'react-image-annotate'
function ImageAnnotator() {
return (
<ReactImageAnnotate
selectedImage="https://images.unsplash.com/photo-1561518776-e76a5e48f731?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80"
// taskDescription="# Draw region around each face\n\nInclude chin and hair."
// images={[
// { src: 'https://example.com/image1.png', name: 'Image 1' },
// ]}
// regionClsList={['Man Face', 'Woman Face']}
/>
)
}
export default ImageAnnotator
I'm using Next.js if that matters
UPDATE 1
I tried using this babel plugin as suggested by Alejandro Vales. It gives the same error as before. Here's the babel key in my package.json:
"babel": {
"presets": [
"next/babel"
],
"plugins": [
[
"#babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"#babel/plugin-transform-modules-commonjs",
{
"allowTopLevelThis": true
}
]
]
}
I would say that the issue relies in the library itself by what they replied in here (similar bug) https://github.com/UniversalDataTool/react-image-annotate/issues/90#issuecomment-683221311
Indeed one way to fix it I would say is adding babel to the project so you can transform the imports in your project to require automatically without having to change the code on your whole project.
This is the babel package you are looking for https://babeljs.io/docs/en/babel-plugin-transform-modules-commonjs
Another reason for this could be an outdated version of your package, as some people report to have this fixed after using a newer version of Create React App (https://github.com/UniversalDataTool/react-image-annotate/issues/37#issuecomment-607372287)
Another fix you could do (a little crazier depending on your resources) is forking the library, creating a CJS version of the lib, and then pushing that to the library, so you and anybody else can use that in the future.
I got a tricky solution!
Problem is that react-image-annotate can only be imported in client-side(SSR got error for import keyword)
So, let react-image-annotate in Nextjs be imported only in client side
(https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr)
in Next Page that needs this component, You can make component like this
import dynamic from "next/dynamic";
const DynamicComponentWithNoSSR = dynamic(() => import("src/components/Upload/Annotation"), { ssr: false });
import { NextPage } from "next";
const Page: NextPage = () => {
return (
<>
<DynamicComponentWithNoSSR />
</>
);
};
export default Page;
Make component like this
//#ts-ignore
import ReactImageAnnotate from "react-image-annotate";
import React from "react";
const Annotation = () => {
return (
<ReactImageAnnotate
labelImages
regionClsList={["Alpha", "Beta", "Charlie", "Delta"]}
regionTagList={["tag1", "tag2", "tag3"]}
images={[
{
src: "https://placekitten.com/408/287",
name: "Image 1",
regions: [],
},
]}
/>
);
};
export default Annotation;
When attempting to transpile the Spacing.js file, it results in an undefined import even when styled-components was seemingly being imported and used (in the same way) successfully in other files. Even when removing the styled-components babel plugin, a similar error occurs.
.babelrc
{
"presets": [["es2015", { "modules": false }], "react-native"],
"plugins": [
["styled-components", { "displayName": true }],
"react-hot-loader/babel",
"react-native-web",
"transform-decorators-legacy",
"transform-class-properties"
],
"env": {
"production": {
"plugins": [
"transform-react-inline-elements",
"transform-react-constant-elements"
]
}
}
}
Spacing.js - Code before transpilation
import React, { Component, Node } from "React";
import styled from "styled-components";
type Props = {
size: string,
color: string,
fullWidth?: boolean
};
class SpacingComponent extends Component<Props> {
render(): Node {
const { size, color, fullWidth = false } = this.props;
return <Spacing size={size} color={color} fullWidth={fullWidth} />;
}
}
const Spacing = styled.View`
height: ${props => props.size}px;
background-color: ${props => props.color || "transparent"};
width: ${props => {
return props.fullwidth ? "100%" : props.size + "px";
}};
`;
export default SpacingComponent;
Generated code for importing and resolving styled-components
Generated code for using the styled-components library (v3.2.5)
The resulting error
Another example can be seen when removing the styled-components babel plugin from the babelrc, thus the withConfig is not added.
Generated error with no styled-components babel plugin
Generated code making this error
Is babel or webpack adding .default when it doesn't need to, if so, how could I investigate why?
try doing styled(View) instead of styled.View
Not sure if this is going to be helpful to anyone but for me the same error was triggered like this style.something and fixed using an html element eg style.span
I need to add {"plugins": [["import", { "libraryName": "antd-mobile" }]]} to .babelrc from a project generated by create-react-native-app to make ant-design-mobile work in react native.
I have started a new project with create-react-native-app.
Change the .babelrc to this:
{
"presets": ["babel-preset-expo"],
"env": {
"development": {
"plugins": [
"transform-react-jsx-source",
]
}
},
"plugins": [
["import", { "libraryName": "antd-mobile" }]
]
}
Class:
import { Button } from 'antd-mobile';
export class Screen extends React.Component<any,{}>{
render(){
return(
<View>
<Button>Something</Button>
</View>
)
}
}
However, I'm still getting this error on start:
Note: must use https://github.com/ant-design/babel-plugin-import .
For more information, please see https://github.com/ant-design/ant-design-mobile/issues/602
Can anyone point me to a solution?
You can take a look at official react-native app demo: https://github.com/ant-design/antd-mobile-samples/tree/master/react-native
I am implementing the Class extend and i get this error Missing class properties transform.
The Component was
import React from ('react')
const Manna = React.createClass({,
initVal: {
likes: 10,
}
render() {
// code
return {
// code
}
}
});
module.exports = Manna
and changed to
import React from 'react';
export default class Manna extends React.Component {
InitVal: {
likes: 10
}
render() {
// code
return {
// code
}
}
};
This is my configuration in webpack.config.dev.js
{
test: /\.js$/,
loaders: 'babel?presets[]=react,presets[]=es2015,presets[]=stage-0',
include: path.join(__dirname, 'client')
},
I have changed the loader following this answer
Before it was loaders: ['babel']
I have also added to .babelrc the plugin
["transform-class-properties"],
This is the error in the console
Missing class properties transform.
15 | // },
16 |
> 17 | InitVal: {
| ^
18 | likes: 10,
19 | code: "2",
20 | size: 350,
I do not understand why it is complaining now for Missing class properties transform, what is wrong in the component?, everything was working fine before of these changes
Here a gist with the full React component
Try with =
import React from 'react';
export default class Manna extends React.Component {
InitVal = {
likes: 10
}
render() {
// code
return {
// code
}
}
};
Check this
UPDATE
Since we are using stage-0 and transform-class-properties is included in stage-2, we don't have to include it manually in .babelrc under plugins. The following configuration works fine: "presets": ["es2015", "stage-0", "react"].
In the gist at line 5 InitVal is written with an uppercase i while at line 39 is written with a lowercase i: initVal. Additionally render method returns an Object Literal, which is invalid, a single child element as to be returned as explained here.
Here is the official documentation for react components defined as es6 classes.
First of all, I temporarily solved the problem that 'this' keeps becoming undefined through disabling 'babel-preset-es2015' and removing 'es2015' styled codes such as 'import', '() => {}', etc. I'm just wondering the fundamental reason why this problem is happening, so I put the question in here.
My project is using React.js, Webpack, Babel, and Electron to make a desktop application. I built UI using React.js, bundled my jsx file using Babel and Webpack.
This is my jsx file:
const React = require('react')
const ReactDOM = require('react-dom')
let Evet = React.createClass({
handleClick: function () {
this.props.onUserSelect(this.props.anEvet)
},
render: function () {
return (
<div className='well well-sm' onClick={this.handleClick}>
{this.props.anEvet.type}: {this.props.anEvet.kind}
</div>
)
}
})
let EvetInfo = React.createClass({
render: function () {
let apisList = []
this.props.anEvet.apis.forEach((api) => {
apisList.push(<li>{api}</li>)
})
return (
<div className='well well-lg'>
<h2>{this.props.anEvet.type} ({this.props.anEvet.kind})</h2>
<ul>{apisList}</ul>
</div>
)
}
})
let EvetList = React.createClass({
getInitialState: function () {
return {
selectedEvet: {}
}
},
handleSelectEvet: function (anEvet) {
this.setState({ selectedEvet: anEvet })
},
render: function () {
let list = []
this.props.evetsList.forEach((evet, idx) => {
list.push(<Evet key={evet._id} anEvet={evet} onUserSelect={this.handleSelectEvet} />)
})
let info
if (this.state.selectedEvet.kind) info = <EvetInfo anEvet={this.state.selectedEvet} />
return (
<div>
<div className='col-md-4'>{list}</div>
<div className='col-md-8'>{info}</div>
</div>
)
}
})
ReactDOM.render(
<EvetList evetsList={evets} />,
document.getElementById('evetlist')
)
This is my webpack.config.js file.
const path = require('path')
module.exports = {
entry: [
'./app/components/app.js'
],
output: {
path: path.join(__dirname, 'app/js/dist'),
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}]
}
}
When I run my program, I got an error like the below screenshot.
When I remove 'es2015 styled code' and disabling 'babel-preset-es2015' in the 'webpack.config.js' file, it works intendedly. Could you let me know why this error is happening when I use 'es2015' preset to bundle it? I want to use 'es2015' style to make my program. '() => ' notation is so cool and convenient. :)
You can't use fat-arrow functions just because they are "cool and convenient"-- they have different semantics than normal functions. Specifically, they share a lexical this with their containing scope, instead of creating a new this-- and in a React component which will be in a module, the outer this will be undefined.