Home > Software design >  Uncaught TypeError: props.users.map is not a function
Uncaught TypeError: props.users.map is not a function

Time:01-07

Here's the code. I'm still very new to using map() This is my all code link https://github.com/thedreamJK7/My-app2

import React from "react";
import styles from "./CollectionUser.module.css";

const CollectionUser = (props) => {
  return (
    <ul className={styles.ulCollect}>
      {props.users.map((Items) => (
        <li>
          {Items.name} ({Items.age} years old)
        </li>
      ))}
    </ul>
  );
};

export default CollectionUser;

CodePudding user response:

There are some problems in your provided link.

  • You are trying to map through the state, where initial value is a string, instead it should be array.
  • Names of setter functions should be meaningful
  • You don't have key, which is a mandatory in map method See the working example of your code, which I uploaded to CodeSandbox
import React from "react";
import styles from "./CollectionUser.module.css";

const CollectionUser = (props) => {
  return (
    <ul className={styles.ulCollect}>
      {props.users.map((Items, index) => (
        <li key={index}>
          {Items.name} ({Items.age} years old)
        </li>
      ))}
    </ul>
  );
};

export default CollectionUser;

App.js

import React, { useState } from "react";
import AddUser from "./Components/AddUser/AddUser";
import styles from "./App.module.css";
import CollectionUser from "./Components/CollectionUser/CollectionUser";

function App() {
  const [users, setUsers] = useState([]);
  const enteredData = (uName, uAge) => {
    setUsers((prevUserlist) => {
      return [
        ...prevUserlist,
        { id: Math.random().toString(), name: uName, age: uAge },
      ];
    });
  };
  console.log(users);
  return (
    <>
      <div className={styles.container}>
        <AddUser info={enteredData} />
      </div>
      <CollectionUser users={users} />
    </>
  );
}

export default App;

CodePudding user response:

The error you get is very helpful: it suggests the your props.users is not an array. All you need to do is set the initial state to an empty array in App.js, so the line below

const [state, setSatate] = useState('');

would become

const [state, setSatate] = useState([]);

This way react will be able to call the .map function on props.users.

  •  Tags:  
  • Related