moris62
moris62

Reputation: 1045

can not access to my state using map in react

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?

Upvotes: 0

Views: 70

Answers (3)

Jordan
Jordan

Reputation: 950

.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>
  );
}

Upvotes: 0

Pasindu Prabhashitha
Pasindu Prabhashitha

Reputation: 390

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"}])

Upvotes: 0

Sanket Shah
Sanket Shah

Reputation: 3091

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

Upvotes: 3

Related Questions