0

I am trying to learn ReactJS and how Javascript code interacts with the components in ReactJS and am not able to get a simple example to work.

Given below is my index.js file:

class JsBasic extends React.Component{
  render(){

    return(
      var hello = () => alert('hello')
      hello()
  );
}
}

ReactDOM.render(
  <JsBasic/>
  document.getElementById('root')
  );

On doing a npm start, I get the following error:

./src/index.js
Syntax error: Unexpected token (53:6)

  51 | 
  52 |     return(
> 53 |       var hello = () => alert('hello')
     |       ^
  54 |       hello()
  55 |   );
  56 | }

Any help greatly appreciated.

2 Answers 2

3

You can't put variables inside return, try this instead:

class JsBasic extends React.Component{
  render(){
    var hello = () => alert('hello')
    return(hello());
  }
}

ReactDOM.render(
  <JsBasic/>
  document.getElementById('root')
  );
Sign up to request clarification or add additional context in comments.

Comments

1
class JsBasic extends React.Component{
hello = () => {alert('hello')}
 render(){
  return(
   this.hello()
  );
 }
}

Example click here

1 Comment

this.hello() will throw error. Moreover hello is not defined. Check Tiago's answer.

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.