I am creating a game in react and I am having trouble mapping some props.
I am getting the error props is not a function and I am unable to cycle through the game map tiles. I have a suspicion my types might be incorrect this is my first time working with with typescript.
here is my page.tsx
import { GameMapTiles } from "@/components/new-types";
export default function Home() {
const normalGameMap: GameMapTiles = [{ resource: "wood", number: 2 }];
return (
<main>
<GameMap {...normalGameMap} />
</main>
);
}
Here is my component GameMap
const GameMap = (props: GameMapTiles) => {
return (
<div className="somthing">
{props.map(([key, tile], count) => (
<div className="Sometile" key={count} />
))}
{console.log(props)}
</div>
);
};
export default GameMap;
Here are the types that I have created
export type Resource = "wood" | "brick" | "sheep" | "wheat" | "ore";
export type TileData = {
resource: Resource;
number: number;
};
export type GameMapTiles = TileData[];
This is not how you pass down props to components. First, you should name your props:
const GameMap = function({ tiles }: { tiles: GameMapTiles }) {
return (
<div className="something">
{tiles.map()} // ...
</div>
);
};
The typescript syntax is a bit awkward here, but you really do need to write the variable name tiles
twice (or not, but you'd lose the benefit of destructuring). Then you can pass down props like this:
export default function Home() {
const normalGameMap: GameMapTiles = [{ resource: "wood", number: 2 }];
return (
<main>
<GameMap tiles={normalGameMap} />
</main>
);
}