When rendering <MyComponent {...docs} />, I kept the following error:
TypeError: docs.map is not a function
Here is how I am rendering <MyComponent /> from a parent class based component:
import * as React from 'react'
import IDoc from '../types/IDoc'
class Doc extends React.Component
{
public render()
{
const docs : IDoc[] = Defs.getDef();
// Example of map working (not doing anything just for an example)
docs.map(x => x);
return (
<div>
<MyComponent {...docs} />
</div>
)
}
}
For some reason when I pass the docs array to the functional <MyComponent/> component, its not seen as an array. I need to convert it to an Array before using .map() which I would prefer to avoid:
import * as React from 'react'
import IDoc from '../types/IDoc'
// docs is an array isn't?
function MyComponent(docs : IDoc[] )
{
if (Array.isArray(docs) === false)
{
//Its not seen as an array so falls into this
return (
<div>
{ Object.keys(docs).map((index) => {
const doc : IDoc = docs[index];
const name = doc.name;
return (
<div>{name}</div>
)
})
}
</div>
)
}else
{
// what I expected to work but it throws the error
return (
<div>
{ docs.map((doc) => {
return (
<div>{doc.name}</div>
)
})
}
</div>
)
}
}
I thought as I defined docs props as IDocs[] it would have been seen as an array due to the square brackets.
The workaround above works, but obviously I don't want to do this every time I use an array function like map(). I am new to React so would appreciate any pointers. I used create-react-app my-app --scripts-version=react-scripts-ts in case that is helpful.