Parsing error: Unexpected token, expected ","

Viewed 101591

I have below code in react js.

class Posts extends Component {
  render() {
    return (
      {console.log('test')}
    );
  }
}

After running this code I get error which is

Parsing error: Unexpected token, expected ","

   8 |     return (
>  9 |       {console.log('test')}
     |       ^
  10 |     );
  11 |   }
  12 | }

UPDATE

wrapping it up with parent tag returns the same error

>  9 |       <div>
     |       ^
  10 |         {console.log('nothing')}
  11 |       </div>

UPDATE

here is the whole class

import React, { Component } from 'react';
import { connect } from 'react-redux';

class Post extends Component {
  render() {
    return (
      <div>
        {console.log('test')}
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    posts: state
  }
};

export default Post;
5 Answers

You always need to have a wrapping parent JSX tag when returning jsx. Since you don't have any jsx tags it's just invalid javascript. Should be:

class Posts extends Component {
  render() {
    return console.log('test')
  }
}

or if you want the jsx

class Posts extends Component {
  render() {
    return (
      <div>
        {console.log('test')}
      </div>
    )
  }
}

edit (2020-1-19)

jsx now supports empty tags for parent closures:

class Posts extends Component {
  render() {
    return (
      <>
        {console.log('test')}
      </>
    )
  }
}

in react js You have to put a value in the attr.

an example that works

<option selected={this.props.info.gender == 0 ? 'selected' : ''} value='0'>men</option>
<option selected={this.props.info.gender == 1 ? 'selected' : ''} value='1'>female</option>

not working

<option {this.props.info.gender == 0 ? 'selected' : ''} value='0'>men</option>
<option {this.props.info.gender == 1 ? 'selected' : ''} value='1'>female</option>

@Mehrdad Masoumi, have a big mistake, this true:

<option selected={this.props.info.gender == **1** ? 'selected' : ''} value='**1**'>men</option>
<option selected={this.props.info.gender == **0** ? 'selected' : ''} value='**0**'>female</option>

@null use a callback that returns console.log.

Asin

() => console.log('test')

mapStateToProps used by connect method of redux add console.log Before the return method

Related