I’m started learning TypeScript and as of moment I’m converting my React code into TypeScript. Then I have run into this issue I couldn’t fix it. Basically I’m passing a state through props component that have implemented value, and hoping this state will be recognize on the other component but then I’m getting error when I tried to map the state on the other component.
Error from MenuItems.tsx:
Property ‘map’ does not exist on type ‘MenuItemsProps’.ts(2339)
Error from Project.tsx
Type ‘ClassType[]’ is not assignable to type ‘Dispatch<SetStateAction<ClassType[]>>’.
Type ‘ClassType[]’ provides no match for the signature ‘(value: SetStateAction<ClassType[]>): void’.ts(2322)
Here’s the code:
Project.tsx
import Data from '@/assets/data/Data'
const Project = () => {
const [menuItems, setMenuItems] = useState<typeof Data>(Data);
return (
<MenuItems menuItems={menuItems} /> // Error here in menuItems
)
}
MenuItems.tsx
import Data from '@/assets/data/Data'
type MenuItemsProps = {
menuItems: React.Dispatch<React.SetStateAction<ClassType[]>>
}
const MenuItems = (menuItems: MenuItemsProps) => {
return (
<div className='menuitem'>
<h1>sample</h1>
{
menuItems.map((item: ClassType) => { // the Error is coming from map
return <div className='menuitem-list' key={item.id}>
<h2>{item.title}</h2>
</div>
})
}
</div>
)
}
Data.ts
import { ClassType } from "../types/Types";
const portfolios: Array<ClassType> = [
{
id: 1,
title: 'Example1',
},
{
id: 2,
title: 'Example1',
},
{
id: 3,
title: 'Example1',
},
]
export default portfolios;
Types.ts
export type ClassType = {
id: number,
title: string,
}
So what I have tried to use the Dispatch and SetStateAction but unfortunately it was no help
— EDIT —
The issue has been resolve with the help from the comment below:
I have added curly bracket on { menuItems }:
const MenuItems = ({ menuItems }: MenuItemsProps) => {
Then replace this "React.Dispatch<React.SetStateAction<ClassType[]>>" with ClassType[] which the issue:
type MenuItemsProps = {
menuItems: ClassType[] }
2
Answers
Replace "menuItems.map" with "Data.map". You are currently trying to map a props object.
There are a couple of issues here.
There is some invalid JSX:Looks that was just a copy/paste error and has been corrected in an edit.<h2>
is missing its closing tag.menuItems
is the props object. Any props you pass to your components will be given as properties of that object. To access theClassType[]
that the Project component is giving to MenuItems, you need to access themenuItems
property of that object. Thus, you would either have to access it asmenuItems.menuItems
or destructure it:menuItems
prop to beReact.Dispatch<React.SetStateAction<ClassType[]>>
, but that’s a type for a function, not an array (specifically, it’s the type of thesetMenuItems()
function inProject.tsx
). Based on what you’re giving MenuItems in the Project component, you really just want that to be the following: