0

I'm learning Reactjs and trying some ES6 features at the same time. Here's a reactjs component that gives me an error:

import React from "react";

export default class Features extends React.Component {

  function myFunc(x, y=5) {
    return x * y;
  }

  render() {

    return (
        <div>
        <p>This is number {this.props.feature}</p>
        {this.myFunc(4,1)}
      </div>
    );
  }
}

For some reason it does not like the function declaration.

I have tried both syntaxes of function declarations:

myFunc: function (x, y=5) {...}

and

function myFunct(x, y=5) {...}

Why does my IDE highlights the space between "function" and "myFunc" and it throws an error:

./src/js/components/Features.js
Module build failed: SyntaxError: X:/projects/react-gallery/src/js/components/Features.js: Unexpected token (5:11)
  3 | export default class Features extends React.Component {
  4 | 
> 5 |   function myFunc(x, y=5) {
    |            ^
  6 |     return x * y;
  7 |   }

2 Answers 2

4

Get rid of the function keyword. Methods is ES6 classes are defined using the shorthand notation only, so the method definitions should look like this:

export default class Features extends React.Component {

  myFunc(x, y=5) {

  }

  render() {

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

Comments

1

You don't need the word function. You can have

import React from "react";

export default class Features extends React.Component {

myFunc(x, y=5) {
  return x * y;
}

render() {

  return (
      <div>
      <p>This is number {this.props.feature}</p>
      {this.myFunc(4,1)}
    </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.