1

I'm getting started with reactjs and tried a simple example in a tutorial.Syntax error occurs when returning html tags.

Here is the error I'm getting

./src/App.js
Syntax error: C:/Users/react-tutotial/src/App.js: Unexpected token (16:6)

14 |   render() {
   |     return{
16 |       <div>
   |       ^
17 |         <button>Increment</button>
18 |         {this.state.count}

This is the app.js file

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  constructor(){
    super();

    this.state = {
      count : 0
    };
  }
  render() {
    return{
      <div>
        <button>Increment</button>
        {this.state.count} 
      </div>
    };
  }
}

export default App;
1
  • The {...} in return { ... } denote an object literal. An object literal needs to contain a sequence of key: value, pairs, not JSX. Commented Apr 22, 2018 at 0:01

1 Answer 1

9

You should use (/) there, not {/}:

 render() {
    return (                                 // changed this line
      <div>
        <button>Increment</button>
        {this.state.count} 
      </div>
    );                                       // changed this line
  }

And know that ()s there are optional, but if you do remove them, <div> must be in the same line as return, like return <div> an on. (When you break a line after return JavaScript goes nuts.)


Edit:

Ok, I feel like I should elaborate on what "goes nuts" is: when you break a line right after return, JavaScript will basically consider it a return; and ignore the rest. And that is effectively the same as return undefined;. Blame this on JavaScript's ASI (Automatic Semicolon Insertion) "feature".

About why exactly {/} doesn't work: Although when inside a JSX "expression" you can use curly braces to place any JavaScript expression, at that point where the error appears, you are not inside a JSX expression yet. This makes that code be interpreted as regular JavaScript expression. And in regular JavaScript, a curly brace alone either creates a context (where let variables would be local, for instance) or object literals. A return expects an expression. A context is not an expression. And your code is not (nor it should be) a valid object literal.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.