9

I'm using react and am trying to map over an array and create objects:

var levels = this.props.levels.map((level, i) =>
  <img key={i} src={levelImg} className={styles.level} />
);

Is it possible to do something like this:

var levels = this.props.levels.map((level, i) =>
  switch (i) {
    case 1:
      // do something
      break;
    case 2:
      // do something
      break;
    case 3:
      // do something
      break;
  }
  // ...
  <img key={i} src={levelImg} className={styles.level} />
);

I'm getting a syntax error when I try something like that.

1 Answer 1

19

In order to use statements inside an arrow function, you have to delimit the function body by braces ({}) and return a value, just like you would do with "normal" function definitions:

var levels = this.props.levels.map((level, i) => {
  switch (i) {
    case 1:
      // do something
      break;
    case 2:
      // do something
      break;
    case 3:
      // do something
      break;
  }
  // ...
  return <img key={i} src={levelImg} className={styles.level} />;
});

See the MDN documentation for more information.

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

3 Comments

Can't we return the value in each case? I tried returning values and it warned me Arrow function expected a return value array-callback-return but this solution worked without warnings
@DimuthRuwantha: You can. I guess the warning comes from the fact that the linter cannot know whether the input will always match one of the cases. If there is no default clause then it has to assume that the value might match, and if you have no return statement after the switch case then the function wouldn't return anything.
I missed to use a return in default case. it was the issue. once I used a return value in default, warning disappeared.

Your Answer

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