Search code examples
arraysreactjsmap-functionreact-functional-component

How to use map function to list the array in React?


Here is my code:

import React, { FunctionComponent } from 'react'

export const ListPage: FunctionComponent = () => {
 const list = [
  {
    title: 'I like React'
  },
  {
    title: 'I also like Angular'
  }
 ]

 const listTag = () => {
  list.map(
    item => {
     <h1>{item.title}</h1>
    }
  )
 }

 return(
  <listTag/>
 )
}

But I still get the error message and not able to fetch out the array.


Solution

  • Try this one:

    import React, { FunctionComponent } from 'react'
    
    export const ListPage: FunctionComponent = () => {
        const list = [
         {
           title: 'I like React'
         },
         {
           title: 'I also like Angular'
         }
        ];
    
        const ListTag = () => list.map(item => (<h1>{item.title}</h1>))
    
        return (
          <ListTag />
        )
    }
    

    Note: Problem in Your code listed below

    const listTag = () => { //fist letter of component need to be captial
      list.map( // the value of `list.map()` needed to be return
        item => {
        <h1>{item.title}</h1> // here you are not returning the value to map function.
        }
      )
    }
    
    return(
      <listTag/> // If You are using any function component make sure the first letter is also captial.
    )