Uncaught syntax error when compiling vs browsing in Reactjs app - reactjs

I'm compiling my Reactjs application with sbt.
Browser exception
Uncaught SyntaxError: Unexpected token :
Compilation error
Parse Error: Line 2: Unexpected token = In C:\Users\martin\Documents\Web Projects\example-app\app\assets\javascripts\nav.jsx:2 1class Nav extends React.Component { 2 static propTypes = { 3 user: React.PropTypes.object 4 }; 5 6 constructor() {
Reason?
I'm not sure why yet, but the browser (Chrome) likes the syntax one way and the sbt compiler does not.
When I change static propTypes = { to static propTypes: { the compiler no longer complains, but the browser does.
Code
static propTypes: {
user: React.PropTypes.object
};
constructor() {
super();
}
state: {};
componentDidMount() {
$.getJSON("./mock-database/users.json", (json) => {
this.setState({user: json});
});
}

The compiler is probably not setup to enable static class properties. In most cases it's easier to define your proptypes outside of the class and it should compile just fine.
class YourClass extends Component {
render() {
}
}
YourClass.propTypes = {
user: PropTypes.object.isRequired
}

Related

ReactJS Why is do I need static function in this code (Newbee)

I am a newbie to react I cannot understand why the function "renderCategoryDiv" needs to be static.
What am I not getting right?
If I remove static the code won't work
My tools : Visual Studio 2020 .net Core 3 API, NodeJs, and react
My code looks like this
import React, { Component } from 'react'; ...
export class Category extends Component {
static displayName = Category.name;
constructor(props) {
super(props);
this.state = { categories: [], ....
componentDidMount() {
this.populateCategoryData();
}
static renderProductDiv(categories) {
return (
<Row>
some code that works when the function is static
</Row >
);
}
Then I have a async fetch of data

StandardJS and React class export Unexpected token =

Can anyone shed some light on the notice I am getting back from StandardJS?
Parsing error: Unexpected token =
Code is as follows:
export default class foreignDataFormat extends _base {
static input = class ForeignDataFormatInput extends React.Component {
render () {
}
}
}
The error is referring to the second line input = class
In JavaScript, class cannot be defined as static. But method can be defined as static. You would just define (and probably mean to define) the class like:
export default class foreignDataFormat extends _base {
const input = class ForeignDataFormatInput extends React.Component {
static myMethod() {
//... my static method
}
render () {
}
}
}
You may be interested to see this post.

Property 'state' does not exist on type 'FetchPeriod'

I'm trying to learn ReactJS following this tutorial:
Tutorial
I'm new to the programming language so i'm clueless as to what to do now.
When I try to add the "Fetchemployee.tsx" file, I get an error at the this.state method.
(TS) Property 'state' does not exist on type 'FetchPeriod'
This is the code:
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import { Link, NavLink } from 'react-router-dom';
interface FetchPeriodDataState {
periodList: PeriodData[];
loading: boolean;
}
export class FetchPeriod extends React.Component<RouteComponentProps<{}>, FetchPeriodDataState> {
constructor(props) {
super(props);
this.state = { periodList: [], loading: true };
fetch('api/Period/Index')
.then(response => response.json() as Promise<PeriodData[]>)
.then(data => {
this.setState({ periodList: data, loading: false });
});
// This binding is necessary to make "this" work in the callback
this.handleDelete = this.handleDelete.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}
And then later on I have the PeriodData class:
export class PeriodData {
PeriodId: number = 0;
Description: string = "";
PeriodOwner: string = "";
PeriodName: string = "";}
The this.state and this.setState methods are giving the errors in the title, and I can't seem to find a fix.
One of possible causes of the problem is missing the React type definitions
Therefore you can try to install them:
npm install --save-dev #types/react #types/react-dom
Without the types installed, TS can't properly infer the props needed for JSX elements.

Passing route parameter to ReactJS constructor results in TS7006

I am having difficulties understanding how I can pass a route parameter to a ReactJS. I have the following code:
import * as React from "react";
import { RouteComponentProps } from "react-router";
import "isomorphic-fetch";
interface IFetchProject {
project: IProject;
loading: boolean;
}
export class Project extends React.Component<RouteComponentProps<{}>, IFetchProject> {
constructor(props) {
super(props);
console.log("this.props", this.props);
let project: IProject = {} as IProject;
this.state = {
project: project, loading: true
};
fetch("api/Projects/"+ this.props.match.params.id)
.then(response => response.json() as Promise<IProject>)
.then(data => {
this.setState({ project: data, loading: false });
});
}
}
(Some code omitted since the error occurs in this part)
The compiler complains about constructor(props) with this error:
TS7006 (TS) Parameter 'props' implicitly has an 'any' type.
The basic end goal is to have access to the route parameter in the constructor so I can use the parameter to get the correct data from my API.
Fixed the problem by replacing:
constructor(props) {
with
constructor(props: RouteComponentProps<{}>) {
Not sure if this is the correct way to do it, but it solved my problem.

Babel 6 making super constructor call to parent throws exception

I upgraded to babel version 6 and I am using "es2015", "react", "stage-0" as presets. I am working with react using es6 syntax.
Everything was working fine until the upgrade. After the upgrade I started to get exceptions in places where I make super call to parent constructor.
For example for the following class:
class childForm extends ParentForm {
constructor(props, context) {
console.log("this get printed.");
super(props, context);
console.log("this is not printed");
}
...
}
class ParentForm extends React.Component {
constructor(props, context) {
console.log("this is printed");
super(props, context);
console.log("this is printed too");
}
...
}
class AnotherComponent extends React.Component {
constructor(props) {
super(props);
this.state = {};
myService.findById(this.props.params.id).then(result => {
this.setState({result: result});
}).catch(err => {
/**** Error is catched here ******/
console.log(err);
});
}
render(){
return <div>{this.state.result && <ChildForm/>}</div>
}
}
I got the following errors on the console:
TypeError: (0 , _typeof3.default) is not a function(…)
ReactCompositeComponent.js?cd59:443 Uncaught (in promise) TypeError: Cannot read property 'context' of null(…)
React function that throws the error is the following function. The exception raised at ReactCompositeComponentMixin.updateComponent
updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) {
var inst = this._instance;
var nextContext = this._context === nextUnmaskedContext ? inst.context : this._processContext(nextUnmaskedContext);
....
If I carry all the functionalities of the parent class to child class, it works as expected. Do anyone encountered a similar problem?
Also is it possible to have better exception messages using some library or plugin for react?
This might be an issue around class compilation. It looks like it can cause an error currently if the child class is declared before the superclass.
Trying this on babeljs.io currently results in an error:
class A extends B {
constructor(x) {
super(x);
}
}
class B {
constructor(x) {
console.log(x);
}
}
new A('a');
Try changing the order of the class definitions:
class ParentForm extends React.Component {
constructor(props, context) {
super(props, context);
}
...
}
class childForm extends ParentForm {
constructor(props, context) {
super(props, context);
}
...
}
EDIT: It seems that Chrome's classes behave pretty much the same, Uncaught ReferenceError: B is not defined(…) is thrown at declaration.
Installing babel-runtime#6.3.19 should solve the problem. Checkout the issue https://phabricator.babeljs.io/T6644

Resources