0

I have a state and I want use map to go through it,

function App() {
const [cardlayouts,setCardLayouts]=useState({id:"1",title:"title1",img:{pic1},text:"text1"})
return (
<div className="App">
      {
      cardlayouts.map(s=><CardLayout id={s.id} title={s.title} img={s.img} text={s.text}/>)
      }
</div>
);
}

I get an error which says cardlayouts.map is not a function,any idea?

moris62
  • 983
  • 1
  • 14
  • 41

3 Answers3

3

This is because you are trying map on the object. Your cardlayouts is object. You can use map only on array

Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
  • so i need to add more items? – moris62 Jul 21 '21 at 16:18
  • No you need to make it and array of object like this: ```const [cardlayouts,setCardLayouts]=useState([{id:"1",title:"title1",img:{pic1},text:"text1"}])``` – Sanket Shah Jul 21 '21 at 16:19
  • thanks it works could you please tell me what does the second part does in my array I mean the setCardLayouts? – moris62 Jul 21 '21 at 16:26
  • ```setCardLayouts``` is use to set the value of your ```cardlayouts```. If you want to learn more about ```useState``` hook refer this: https://stackoverflow.com/questions/53165945/what-is-usestate-in-react – Sanket Shah Jul 21 '21 at 16:28
0

Edit your code like this. To map you should have an array. But you have given a object instead.

const [cardlayouts, setCardLayouts] = useState([{id:"1",title:"title1",img: 
{pic1},text:"text1"}])
0

.map() is an array method, but your state isn't an array.

You don't need to use map in this situation. Just access the keys like normal:

function App() {
  const [cardlayouts,setCardLayouts] = useState({
    id:"1",
    title:"title1",
    img:{pic1},
    text:"text1"
  })

  return (
    <div className="App">
      <CardLayout 
        id={cardlayouts.id} 
        title={cardlayoust.title} 
        img={card.img} 
        text={s.text}
      />
    </div>
  );
}

Or, make the state an array and map over it like this:

function App() {
  const [cardlayouts,setCardLayouts] = useState([
    {
      id:"1",
      title:"title1",
      img:{pic1},
      text:"text1"
    }
  ])

  return (
    <div className="App">
      {cardlayouts.map(layout => (
        <CardLayout
          id={layout.id} 
          title={layout.title} 
          img={layout.img} 
          text={layout.text}
        />
      ))}
    </div>
  );
}
Jordan
  • 868
  • 1
  • 8
  • 25