Home > Net >  Problem while returning an array on react: Uncaught TypeError: Cannot read properties of undefined (
Problem while returning an array on react: Uncaught TypeError: Cannot read properties of undefined (

Time:04-14

I am triying to return p in a div from an array that come from a useState hook, but give me this error:Uncaught TypeError: Cannot read properties of undefined (reading 'items')

Image

function App(){

        
    const [items, setLab] = useState(["a", "b", "c"])

    console.log(items)
    return (
        <div> laberinto
        {this.items.bind(this).map((item) => {
             <div>
                 <p>{item}</p> 
             </div>
         })
        }
        </div>
    )

}

 
render(
    <App/>,
    document.getElementById('app'),
);

CodePudding user response:

Your App component is a functional component (not a class component), so you don't need to use this keyword.

{items.map((item) => {
  <div>
    <p>{item}</p>
  </div>
 })
}

More detailed about Functional and Class components here: https://reactjs.org/docs/components-and-props.html#function-and-class-components

CodePudding user response:

Issues

  1. this is simply undefined in React function components.
  2. Array.prototype.map callback needs to return a value being mapped to.

Solution

  • Remove any this references.
  • Return JSX from the .map callback. Don't forget to include the React keys.

Explicit return statement in the function body:

function App() {
  const [items, setLab] = useState(["a", "b", "c"]);

  return (
    <div>
      laberinto
      {items.map((item) => {
        return (
          <div key={item}>
            <p>{item}</p> 
          </div>
        );
      })}
    </div>
  );
}

Implicit return without a function body:

function App() {
  const [items, setLab] = useState(["a", "b", "c"]);

  return (
    <div>
      laberinto
      {items.map((item) => (
        <div key={item}>
          <p>{item}</p> 
        </div>
      ))}
    </div>
  );
}
  • Related