-1

I'm working on a small react project, and I'm trying to map over an array, and display the names (in react).

I've been trying to find a solution to this error (.map is not a function), and the only suggestion I found was adding the index as a key. It doesn't seem to be solving it, any help would be greatly appreciated!

dil-emma
  • 11
  • 1
  • The problem is your utility function returning a string rather than an array when the passed arr parameter is too short. Also, don't use index as a key unless you want headaches with state lifecycle, always use a unique property of each iterated element. – pilchard Mar 26 '21 at 00:44

2 Answers2

-1

Your groups is not an array hence the .map is not a part of the groups. I tried your code sandbox and the groups is having following value.

3 people should be one group!

Check how is your groups being set.

for the workaround until you fix your group value you can do something like this.

import React, { useState } from "react";
import { shuffleArray, createGroups } from "./utils";
import "./styles.css";
//TODO groups should be at least 3 people
//MAYBE also add option people per group

const App = () => {
  const [names, setNames] = useState("");
  const [numGroup, setNumGroup] = useState(2);

  const handleNames = (e) => {
    e.preventDefault();
  };

  const shuffledArr = shuffleArray(names.split(" "));
  const groups = createGroups(numGroup, shuffledArr);

  return (
    <div className="App">
      <h1>Coffee Groups</h1>
      <form className="form" onSubmit={handleNames}>
        <textarea
          name="listOfNames"
          type="text"
          value={names}
          onChange={(e) => setNames(e.target.value)}
        />
        <div className="button">
          <label>groups</label>
          <input
            min="2"
            className="numInput"
            type="number"
            value={numGroup}
            onChange={(e) => setNumGroup(e.target.value)}
          />
          <button type="submit" onClick={() => console.log(groups)}>
            Run
          </button>
        </div>
      </form>
      <div>
        {Array.isArray(groups) && groups.map((group, idx) => {
          return (
            <ul key={idx}>
              <li>Group {idx + 1}</li>
              {group.map((person, idx) => {
                return <li key={idx}>{person}</li>;
              })}
            </ul>
          );
        })}
      </div>
    </div>
  );
};

export default App;

Yadab
  • 1,767
  • 1
  • 10
  • 16
-2

On codesandbox, if you hover over line 16 const groups = createGroups(numGroup, shuffledArr); you'll see that groups is any[] | "3 people should be one group". Since in some cases groups is not an array, line 43 JS complains that .map() does not exist on a string.

You can fix this by making createGroups only returning an array, and then instead of groups? try groups.length >= 3?

codeAligned
  • 179
  • 2
  • 3
  • 9