Elder
Elder

Reputation: 363

Map function React

I have a grouped object. Then I exchanged the object for the array: const objectToArray = ["Since", Array(7)]. Then I want to map the array to get it objectToArray[0] (shows picture) and objectToArray[1] (shows list of question). I want to show the category photo and the list of questions below.

import { groupBy } from 'lodash';
import QuestionsListItem from './QuestionListItem';

const images = require.context('../../img', true);
const imagePath = (name) => images(name, true);

const QuestionsList = ({ questions }) => {
  const groupByList = groupBy(questions.questions, 'type');
  const objectToArray = Object.entries(groupByList);

  const questionListItem = objectToArray.map((array) => (
    <img src={imagePath(`./${array[0]}.png`)} alt="star" />,
    array[1].map((question) => (
      <QuestionsListItem
        key={question.id}
        question={question}
      />
    ))));


  return (
    <div>
      <ul>
        { questionListItem }
      </ul>
    </div>
  );
};

The code shows me a error: Line 14: Unexpected use of comma operator no-sequences This is it <img src={imagePath(./${array[0]}.png)} alt="star" />,

When you delete a comma, it gets an error

  Line 15:  Parsing error: Unexpected token, expected ","

  13 |   const questionListItem = objectToArray.map((array) => (
  14 |     <img src={imagePath(`./${array[0]}.png`)} alt="star" />
> 15 |     array[1].map((question) => (
     |     ^
  16 |       <QuestionsListItem
  17 |         key={question.id}
  18 |         question={question}

How to solve this problem? thanks in advance :)

Upvotes: 0

Views: 115

Answers (1)

Colin Ricardo
Colin Ricardo

Reputation: 17269

Kind of an obscure error, but the way you have it now, you'd be returning multiple nodes at the same level, so you need to wrap it with something.

Try this:

const questionListItem = objectToArray.map(array => (
  <React.Fragment>
    <img src={imagePath(`./${array[0]}.png`)} alt="star" />
    array[1].map((question) => (
    <QuestionsListItem key={question.id} question={question} />)
  </React.Fragment>
));

Upvotes: 1

Related Questions