I am quite new to React and wonder how this should work:
class App extends Component {
> 4 | state = {
| ^
5 | bands: [],
6 | concerts: []
7 | }
here the error message:
ERROR in ./src/App.js
Module build failed: SyntaxError: Unexpected token (4:8)
Edit (the whole component):
import React, { Component } from 'react'
class App extends Component {
state = {
bands: [],
concerts: []
}
render() {
return <div>hei</div>
}
}
export default App
Some solution to this?
If the code is really as shown, you're trying to use a language feature ("class fields") that isn't in the language yet, it's still a stage 3 proposal. You need to ensure whatever transpiler you're using handles transpiling that.
If you don't want to use class fields, define your state property in a constructor:
class App extends Component {
constructor(...args) {
super(...args);
this.state = {
bands: [],
concerts: []
};
}
render() {
return <div>hei</div>
}
}
One option would be to put the state inside your constructor:
class App extends Component {
constructor(props) {
super(props)
this.state = {
bands: [],
concerts: []
};
}
render() {
// Here you can access to this.state
return <div>hei</div>
}
}
Related
Background
I created a fully functional component. The component has state and props, and there are many methods inside. My component should work differently according to the os(ios / android). So I solved this problem by if statement like below.
if( platform.os == 'ios') { ... } else { ... }
The problem was that as the code volume increased, there was a problem with readability, and I decided to make a separate component for IOS and for Android. The first thing that came to mind was inheritance because ES6 and Typescript Support Class. The picture of concept is this.
However, React does not recommend inheritance. So I was just going to hand over the functions overridden by props to the Speech component in the SpeechIOS component's render function.
The code is as follows.
Speech.tsx
type Props = {
team: number,
onSpeechResults: (result: string) => void
...
}
type States = {
active: boolean;
error: string;
result: string;
...
};
export default class Speech extends Component<Props,States> {
state = { ... };
constructor(props: Props) {
super(props);
...
}
// render
render() {
...
return (
<ImageBackground source={require("../images/default-background.jpeg")} style={styles.full}>
...
</ImageBackground>
);
}
sendCommand = (code: number, speed: number, callback?: () => void) => { ... }
getMatchedSpell = (spellWord: string): { code: number, speed: number } => { ... }
onSpeechResults(e: Voice.Results) { ... };
...
}
SpeechIOS.tsx
import Speech from './Speech';
type Props = {}
type States = {}
export default class SpeechIOS extends Component<Props,States> {
constructor(props: Props) {
super(props);
...
}
// render
render() {
...
return ( <Speech team="1" onSpeechResults={this.onSpeechResults}></Speech> );
}
sayHello() {
console.log("Hello!!");
}
// I want that Speech Component call this onSpeechResults function
onSpeechResults(result: string) {
this.setState({...});
let temp = this.getMatchedSpell( ... ); // which is in Speech Component
this.sendCommand( 10, 100 ... ); // which is in Speech Component
this.sayHello(); // which is in SpeechIOS component only
... other things..
};
}
Problem.
As you can see, the onSpeechResults which is in SpeechIOS Component use some functions in Speech Component and in SpeechIOS Component also.
So, How to solve this problem? Should I use Inheritance?
Alternatively, break out any common logic into a utility function like SpeechUtil.ts, a whole new file that holds this shared logic and each util function, and exports them. Then, each component separately imports them. That ensures that if you ever update that logic it affects both components
You should define a top level component that defines the shared props and methods, and use those to render either your ios or android component. pass the props and methods to the children. This is composition which is favored over inheritance in react. example:
class Speech extends React.Component {
state ={shared: 'state'}
sharedMethod = () => {
this.setState({blah: 'blah})
}
render() {
const Root = Platform.select({
ios: SpeechIOS,
android: SpeechAndroid
})
return <Root onClick={this.sharedMethod} shared={this.state.shared}/>
}
}
You can use React.createRef for this purpose.
Below is an example code.
import Speech from './Speech';
type Props = {}
type States = {}
export default class SpeechIOS extends Component<Props, States> {
constructor(props: Props) {
super(props);
this.speech = React.createRef();
}
// render
render() {
...
return (<Speech ref={this.speech} team="1" onSpeechResults={this.onSpeechResults}></Speech>);
}
sayHello() {
console.log("Hello!!");
}
// I want that Speech Component call this onSpeechResults function
onSpeechResults(result: string) {
this.setState({ ...});
let temp = this.speech.current.getMatchedSpell(... ); // which is in Speech Component
this.sendCommand(10, 100 ... ); // which is in Speech Component
this.sayHello(); // which is in SpeechIOS component only
...other things..
};
}
If you need to specify initial state in a class, I see people did this
class App extends React.Component {
constructor() { super(); this.state = { user: [] } }
render() {
return <p>Hi</p>
}
}
but what's wrong without a constructor?
class App extends React.Component {
state = { user: [] }
render() {
return <p>Hi</p>
}
}
but what's wrong without a constructor?
There is nothing "wrong" with it. But it uses the class properties proposal which is not officially part of the language yet (since you tagged the question with ecmascript-6: It is not part of ES6). So you have to correctly configure your build system to be able to use it (in addition to what's needed for JSX).
I'm learning React and I'm not sure how to setup this pattern. It could be something really easy I'm just missing.
I have a main component that controls state. It has all of the functions to update state and passes these down to child components via props. I've simplified the code to focus on one of these functions.
Here's the component now, all works as it should:
ManageMenu.js
import React from 'react'
class ManageMenu extends React.Component {
constructor() {
super()
this.toggleEditing = this.toggleEditing.bind(this)
// Set initial state
this.state = {
menuSections: []
}
}
toggleEditing(id) {
const menuSections = this.state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
this.setState({ menuSections })
}
render() {
return (
...
)
}
}
export default ManageMenu
The toggleEditing is passed via props to a child component that uses it to render an editing form if the edit button is clicked.
I have about 10 of these different functions in this component and what I would like to do is move them to an external lib/methods.js file and then reference them. Below is the code I would like to have, or something similar, but React doesn't like what I'm doing. Throws a syntax error:
Failed to compile.
Error in ./src/components/ManageMenu.js
Syntax error: Unexpected token
toggleEditing(id, menuSectionId, this.state, this)
Here is what I would like to do...
lib/methods.js
const toggleEditing = function(id, state, that) {
const menuSections = state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
that.setState({ menuSections })
}
module.exports = {
toggleEditing
}
And then in my component:
ManageMenu.js
import React from 'react'
import { toggleEditing } from '../lib/methods'
class ManageMenu extends React.Component {
constructor() {
super()
// Set initial state
this.state = {
menuSections: []
}
}
toggleEditing(id, this.state, this)
render() {
return (
...
)
}
}
export default ManageMenu
Any help is appreciated, thanks!
Thanks to #Nocebo, the answer on how to externalize functions is here:
Externalise common functions in various react components
In my particular situation,
I need to remove the “floating” toggleEditing(id, this.state, this) call in the middle of nowhere. Update: This error happens “because it is invoking a method within a class definition.” (see Pineda’s comment below)
Remove the leading this. on the right side of the this.toggleEditing statement in constructor()
Update the function in lib/methods.js to remove the state and that variables since its bound to this in the constructor()
See updated code below.
ManageMenu.js
import React from 'react'
import { toggleEditing } from '../lib/methods'
class ManageMenu extends React.Component {
constructor() {
super()
this.toggleEditing = toggleEditing.bind(this)
// Set initial state
this.state = {
menuSections: []
}
}
render() {
return (
...
)
}
}
export default ManageMenu
lib/methods.js
const toggleEditing = function(id) {
const menuSections = this.state.menuSections
menuSections.map(key => (key.id === id ? key.details.editing = id : ''))
this.setState({ menuSections })
}
module.exports = {
toggleEditing
}
You're error arises because you are invoking toggleEditing in your ManageMenu.js class definition rather than defining a function.
You can achive what you want by setting a local class member this.toggleEditing to the bound function returned by the .bind method and do so within the constructor:
import React from 'react'
import { toggleEditing } from '../lib/methods'
class ManageMenu extends React.Component {
constructor() {
super()
this.state = {
menuSections: []
}
// bind external function to local instance here here
this.toggleEditing = toggleEditing.bind(this);
}
// don't invoke it here, bind it in constructor
//toggleEditing(id, this.state, this)
render() {
return (
...
)
}
}
export default ManageMenu
I am trying to figure out how to write a Component in a MERN app.
This is my best effort, taking account of this advice on how to go about it?
import React from 'react';
import ReactDOM from 'react-dom';
import * as ReactBootstrap from 'react-bootstrap'
var GreeterMessage = require('GreeterMessage');
var GreeterForm = require('GreeterForm');
class Greeter extends React.Component {
getDefaultProps: function () {
return {
name: 'React',
message: 'This is the default message!'
};
},
getInitialState: function () {
return {
name: this.props.name,
message: this.props.message
};
},
handleNewData: function (updates) {
this.setState(updates);
},
render: function () {
var name = this.state.name;
var message = this.state.message;
return (
<div>
<GreeterMessage name={name} message={message}/>
<GreeterForm onNewData={this.handleNewData}/>
</div>
);
}
};
When I save this and run web pack in my terminal to check everything, I get this feedback:
ERROR in ./app/components/Greeter.jsx
Module build failed: SyntaxError: Unexpected token (9:19)
7 |
8 | class Greeter extends React.Component {
> 9 | getDefaultProps: function() {
| ^
10 | return {
11 | name: 'React',
12 | message: 'This is the default message!'
# ./app/app.jsx 19:14-32
I can't find any resources to help me figure out what a token is, let alone when they are expected or unexpected.
Can anyone see where I'm getting this wrong? I've just finished 5 separate udemy courses that are supposed to be an intro to react and MERN, and I can't get the first step to work.
It looks like your mixing the older React.createClass syntax with the latest ES6 class notation. You can't mix and match :)
You're also using both CommonJS and ES6 versions of importing code into your file. Although this won't break the code (unless you're using a setup that doesn't support import, I would advise dine consistently wouldn't go amiss.
Here is an example of an amended version of your code to use the ES6 syntax:
import React from 'react';
import ReactDOM from 'react-dom';
import * as ReactBootstrap from 'react-bootstrap'
import GreeterMessage from 'GreeterMessage');
import GreeterForm from 'GreeterForm');
// sets the default values for props
Greeter.defaultProps = {
name: 'React',
message: 'This is the default message!'
};
class Greeter extends React.Component {
constructor(){
super();
// sets the initial state
this.state = {
name: this.props.name,
message: this.props.message
};
// due to this not being bound intrinsically to event handlers,
// it's advisable to do it here so that the reference to
// this.setState works as expected:
this.handleNewData = this.handleNewData.bind(this);
}
handleNewData(updates) {
// `this` is not automatically bound to event handlers in ES6
// Ensure that it is bound by using `.bind` (see constructor)
// OR with ES6 arrow functions
this.setState(updates);
}
render() {
var name = this.state.name;
var message = this.state.message;
return (
<div>
<GreeterMessage name={name} message={message}/>
<GreeterForm onNewData={this.handleNewData}/>
</div>
);
}
};
Issue is you are mixing es5 and es6 way of writing the react component. I will suggest you to write in es6. Pasted useful links in the last, refer those links for more details.
Write it like this:
class Greeter extends React.Component {
constructor(){
super();
this.state = {
name: this.props.name,
message: this.props.message
}
this.handleNewData = this.handleNewData.bind(this);
}
handleNewData (updates) {
this.setState(updates);
}
render () {
var name = this.state.name;
var message = this.state.message;
return (
<div>
<GreeterMessage name={name} message={message}/>
<GreeterForm onNewData={this.handleNewData}/>
</div>
);
}
};
Greeter.defaultProps = {
name: 'React',
message: 'This is the default message!'
};
Links:
DefaultProps
es6 class
React DOC
No Autobinding of methods
Due I refactor my code to ES6, I move all defaults to SomeClass.defaultProps = { ... }.
Suppose a situation, when there is a class hierarchy, and I need to keep some defaults to whole hierarchy. But the problem is that defaultProps not work for classes that are extended:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
}
class OneOfImplementations extends AbstractComponent {
constructor(props) { super(props) }
}
//Problem: hierarchy defaults doesn't work
AbstractComponent.defaultProps = { name: 'Super' }
Fiddle example
P.S. I'm wondering where is the best place to keep commons (variables/functions) for the whole hierarchy? Maybe do something like this at AbstractComponent:
constructor(props) {
super(_.assign(props, {
commonValue: 128,
commonCallback: _.noop
}));
}
But the problem is that's become impossible to override one of properties from a subclass
Alternatively if you're using the stage: 0 stage: 2 preset in Babel (or the transform directly) you can use es7's proposed static property:
class AbstractComponent extends React.PureComponent {
static defaultProps = { name: 'Super' }
// Bonus: you can also set instance properties like this
state = {
someState: true,
}
// ^ Combined with new arrow binding syntax, you often don't need
// to override the constructor (for state or .bind(this) reasons)
onKeyPress = () => {
// ...
}
}
It seems like the order of declaration of the "defaultProps" property is important:
class AbstractComponent extends React.Component {
constructor(props) { super(props) }
render() {
return <div>Prop: [ {this.props.name} ]</div>
}
}
AbstractComponent.defaultProps = { name: 'Super' }
class ComponentImpl1 extends AbstractComponent {
constructor(props) { super(props) }
}
// works
http://jsfiddle.net/jwm6k66c/103/