Getting Uncaught TypeError: boxes.map is not a function

68 views Asked by At

not sure what i am doing wrong but when i am trying to detect a face in my app I am getting the below error messagereact error

what am i doing wrong? see code below

import React from 'react'; import './FaceRecognition.css';

const FaceRecognition = ({ imageUrl, boxes }) => {
  return (
    <div className='center ma'>
      <div className='absolute mt2'>
        <img id='inputimage' alt='' src={imageUrl} width='500px' heigh='auto' />
        {boxes.map((box, i) => {
          return (
            <div
              key={i}
              className='bounding-box'
              style={{ top: box.topRow, right: box.rightCol, bottom: box.bottomRow, left: box.leftCol }}></div>
          );
        })}
      </div>
    </div>
  );
};

export default FaceRecognition;
2

There are 2 answers

0
user2465134 On BEST ANSWER

boxes is probably not an array. console.log(boxes) before you return your JSX to see what boxes actually is

0
Jesus Angel Rodriguez Martinez On

Let's take a look at the following example:

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

const Home = () => {
    [items, setItems] = useState();
    useEffect(() => {
        setItems(["first","second","etc"]);
    }, []);
    return (
        <div><List items={items} /></div>
    );
};

This will cause the same error because items is not an array at first instance, it's not initialized:

[items, setItems] = useState();

In this case useState receives a parameter as initial state. To fix this error you should initialize the state with an empty array in order to use the map method:

[items, setItems] = useState([]);

So, following the lifecycle, it will render the List component given an empty array, and then the map method will be triggered. You can also fix this by giving a default param when the object is not defined or the prop is not passed.

const List = ({ items = [] }) => {
  return (
    <div>{items.map(item => <p>{item}</p>)}</div>
  );
}

In this way, even if you don't pass the item prop, it will have an empty array.