ReactJS - Unexpected token '.' error - reactjs

I am starting with my react project on VS2013 working together with ASP.NET MVC. I have configured webpack and configuration seemed working well until I tried to implement the following class.
class Hello extends React.Component {
this.state = { visible: true }
render() {
/** Method definition **/
...
}
I am getting an error Unexpected Token at '.' at 'this.state'. I have already check es2015 is set as babel preset. If I remove state and toggleVisibility assignments, webpack bundles OK.
Any idea what else can I try?

It's a class so the correct syntax should be
class Hello extends React.Component {
state = { visible: true }
render() {
/** Method definition **/
...
}
Also, the recommended way of defining initial state should be
class Hello extends React.Component {
constructor(props) {
super(props)
this.state = { visible: true }
}
render() {
/** Method definition **/
...
}

You should define this.state in a constructor like
constructor(props) {
super(props);
this.state = {
visible: true
};
}
Hence, your code should be
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true
};
}
render() {}
}
From React docs:
The constructor is the right place to initialize state. If you don't
initialize state and you don't bind methods, you don't need to
implement a constructor for your React component.

Related

React: How to read state from within handler function?

I'm new to React working on an existing React component (that appears to be built in an older style - no hooks).
I want to read and set state within a handler function. I have the following code:
export default class MyComponent extends React.Component {
static defaultProps = {
data: {}
};
constructor(props) {
super(props);
// Other states
this.state.myState = false;
};
handleMyChange() {
if (!this.state.myState) {
console.log("hello world");
}
}
However I get the error Cannot read properties of undefined.
I've tried various like state.myState but am not really sure what I should be doing.
Can anyone point me in the right direction?
In order to have this context in your function, you will need to bind it in the constructor first
Here is a small example is taken from the official doc:
import React from "react";
export default class SayHello extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello!" };
// This line is important!
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert(this.state.message);
}
render() {
// Because `this.handleClick` is bound, we can use it as an event handler.
return <button onClick={this.handleClick}>Say hello</button>;
}
}

TypeErro: Cannot read property 'data' of null

Am new to reactjs and am implementing a to do app using controlled component but am getting an error. Type Error: this.state is null!
Have you initialized your state in a constructor? You can do this by creating a constructor function in your class, e.g.
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = {todoList: []};
}
Then you can add your todo's by doing this:
let todoListChange = this.state.todoList;
todoListChange.push("Clean my toilet");
this.setState({todoList: todoListChange});
You have not initialized your state. Default state is null.
class App from React.Component {
constructor (props) {
super(props);
this.state = { todos: [] }
}
render () {
// your implementation
}
}

React native state declaration difference

What's the difference between declaring state as given below:
export default class BlackFade extends React.Component {
state = { fListData : [] }
}
export default class BlackFade extends React.Component {
constructor(props) {
super(props);
this.state = { fListData : [] }
}
}
Both of them are doing the same job
First one state = { fListData : [] } is making use of
class property proposal which is stage 3 proposal under the hood which is doing the same job as :
constructor(props) {
super(props);
this.state = { fListData : [] }
}
NOTE: There are total 4 stages of a proposal after that , proposal will be a part of a Language
You can compare and check both of them on Babel Transpiler

Is the call to super(props) in an ES6 class important?

Suppose I've the following class:
class Tabs extends React.Component {
displayName: Tabs;
static propTypes = {
selected: React.PropTypes.number,
children: React.PropTypes.oneOfType([
React.PropTypes.array,
React.PropTypes.element
]).isRequired
};
constructor() {
super();
this.state = {
selected: 0,
maxSelected: 0
};
render() {
return(
<div>
{this.props.selected}
{this.props.children}
</div>
);
}
};
I want to know that if passing the following constructor is important:
constructor(props) {
super(props);
}
My current code works just fine but I wanted to know if this is a good practice.
According to Sophie Alpert with the React team it's only necessary to pass props into the constructor if you intend on using this.props inside the constructor. After the constructor is invoked, React attaches the props to the component from the outside.

Warning: getInitialState was defined on DimensionPicker, a plain JavaScript class. This is only supported for classes created using React.createClass

I am trying to write my first react control. Here is what I have written
import React from 'react';
import DimensionPickerAction from '../actions/DimensionPickerActions.js';
import MovieLensAppStore from '../stores/MovieLensAppStore.js';
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], currentItem: '' };
}
getInitialState() {
this.state = {
items: MovieLensAppStore.getAttributes(this.props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
};
}
onSelectionChange(newValue) {
DimensionPickerAction.selectionChange(this.props.dimension, newValue);
}
render() {
var optionNodes = this.state.items.map((item) => {
if (item === this.state.currentItem)
return(<option value="{item}" selected>{item}</option>)
else
return(<option value="{item}">{item}</option>)
});
return(<div><select onchange="onSelectionChange">{optionNodes}</select></div>);
}
}
export default DimensionPicker;
Very surprisingly, I get an error
Warning: getInitialState was defined on DimensionPicker, a plain JavaScript
class. This is only supported for classes created using React.createClass. Did
you mean to define a state property instead?
I find this very confusing because clearly my component derives from React.Component
Eric's comment is correct. You're using ES6 classes, which means that getInitialState is not supported. You'll need to change this:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], currentItem: '' };
}
getInitialState() {
this.state = {
items: MovieLensAppStore.getAttributes(this.props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(this.props.dimension)
};
}
to this:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this.state = {
items: MovieLensAppStore.getAttributes(props.dimension),
currentItem : MovieLensAppStore.getCurrentAttribute(props.dimension)
};
}
What about this, if you like to save the initial state construction somewhere for later use:
class DimensionPicker extends React.Component {
constructor(props) {
super(props);
this._getInitialState = this._getInitialState.bind(this)
this.state = this._getInitialState();
}
_getInitialState() {
return { items: [], currentItem: '' }
}

Resources