Search code examples
javascriptreactjsionic-frameworkionic-react

Return an array of object in a ionic reactjs component


I have this component that is called in my main file, this component displays all the data, the data returns an array

    import React, { Component } from 'react';
    import {
        IonRow,
        IonCol
    } from '@ionic/react';
    
    import data from '../data/data.json';
    
    const BookList: React.FC = () => {
        
        return(
            data.data.map((context) => {
            <IonRow>
                <IonCol size="9">
                    <p>{context.name}</p>
                </IonCol>
                <IonCol size="3">
                    <p>{context.payload}</p>
                </IonCol>
            </IonRow>
            })
        );
        
    };
    
    export default BookList;

And the error is like:

error

somewhere in declaring booklist. Im new to react so its kinda bit hard to understand what the main problem is, I tried to search for any solutions but cant find definite and clear solution that I understand.


Solution

  • Your code was returning an array of elements, see this Type '() => JSX.Element[]' is not assignable to type 'FC<{}>', all you need is to return a single element using <div> or react fragment i.e. <> </>

    Try this:

    const BookList: React.FC = () => (       
      <>
        {data.data.map(({ name, payload }) => (
          <IonRow>
               <IonCol size="9">
                   <p>{name}</p>
               </IonCol>
               <IonCol size="3">
                   <p>{payload}</p>
               </IonCol>
           </IonRow>
        ))}
      </>
    );