Search code examples
reactjstypescriptreact-component

React .map is not a function but cannot pass array


I have my app root and a lazyloaded component.

App root :

import Component from './app/components/component/component.lazy';

class App extends React.Component{

    stuff: stuffType[] = [1, 2 , 3];

    render() {
        return (
           <Component stuff={this.stuff}/>
        );
    }
}


export default App;

Lazy Component:

import React, { lazy, Suspense } from 'react';
import {stuffType} from '../../dto/types';

const Lazycomponent = lazy(() => import('./component'));

const component = (props: {tanks: stuffType[]} & { children?: React.ReactNode; }) => (
  <Suspense fallback={null}>
    <Lazycomponent {...props} />
  </Suspense>
);

export default component;

Component:

const component: React.FC<any> = (stuff: stuffType[]) => {
    return(
       {stuff.map((stuff: stuffType, index: number) => {
           return (
              <div >

              </div>
           )
       })}
    )
}

the above code has no errors after live typechecking and also none in the run console.

however at runtime in the browser I get the error that

TypeError: stuff.map is not a function

Ok. Fine :

const component: React.FC<stuffType[]> = (stuff: stuffType[]) => {

Nope now live typecheck fails in lazy component :

TS2740: Type '{ stuff: stuffType[]; children?: ReactNode; }' is missing the following properties from type 'stuffType[]': length, pop, push, concat, and 28 more.

How can it say this when what I'm giving it is an array?


Solution

  • Props is an object and not an Array.

    interface Props {
      stuff: stuffType[]
    }
    
    const component: React.FC<Props> = props => {
        return(
           {props.stuff.map((stuff: stuffType, index: number) => {
               return (
                  <div >
    
                  </div>
               )
           })}
        )
    }