2

I'm doing my first steps in reactjs. This code should write "ON", but I get error:

App.js: Unexpected token, expected (

Code:

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

class Light extends React.Component {

    constructor(props) {
        super(props);
        this.state = {light:"On"};
    };

    function formatLightState() {
        return <h1>{this.state.light}</h1> ;
    }

    render() {
        return (
        <div>
            {this.formatLightState()}
        </div>
        );
    }
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  renderLight(){
      return <Light />
  }

  render() {
    return (
        <div>
            {this.renderLight()}
        </div>
    );
  }  
}

export default App;

What am I missing?

2 Answers 2

1

Issue is function keyword. To define a function inside react component you don't need to use that.

Write it like this:

formatLightState() {
    return <h1>{this.state.light}</h1> ;
}

Jsfiddle: https://jsfiddle.net/ynx2evyj/

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

1 Comment

thanks!, it worked. i can't belive i wasted so much time for this :(
0

You way of writing the formatLightState function is incorrect. Also you will need to bind the function to access the state. In order to bind you can make use of arrow functions or bind it in the constructor

class Light extends React.Component {

    constructor(props) {
        super(props);
        this.state = {light:"On"};
    };

    formatLightState = () => {
        return <h1>{this.state.light}</h1> ;
    }

    render() {
        return (
        <div>
            {this.formatLightState()}
        </div>
        );
    }
}

class App extends React.Component {
  constructor(props) {
    super(props);
  }

  renderLight(){
      return <Light />
  }

  render() {
    return (
        <div>
            {this.renderLight()}
        </div>
    );
  }  
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>

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.