Could I get some help please with the definition of an interface for the IconArr.primary
property.
I am trying to pass it into PrimarySkills
components --> where I have to define interface but without any luck so far.
I do not want to pass the whole object with both primary and secondary icons, so I can have two separate components but with different input data later.
const iconsArr = {
primary: [
{
id: '0',
imgPath: 'images/techIcons/reactjs.svg',
name: 'React',
},
{
id: '1',
imgPath: 'images/techIcons/nextjs.svg',
name: 'NextJS',
},
],
secondary: [
{
id: '0',
imgPath: 'images/techIcons/csharp.svg',
name: 'C#',
},
{
id: '1',
imgPath: 'images/techIcons/java.svg',
name: 'Java',
},
],
};
const Skills = (props: Props) => {
return (
<div>
<StyledCaption contentString='SKILLS'>PRIMARY</StyledCaption>
<PrimarySkills iconsArr={iconsArr.primary} />
</div>
);
};
in PrimarySkills
Component
interface Props {
iconsArr: {
primary: {
id: string;
imgPath: string;
name: string;
}[];
};
}
const PrimarySkills = (props: Props) => {
return (
<div>
{props.iconsArr.primary.map((icon) => (
<img src={icon.imgPath} alt={icon.name} key={icon.id} height='30' />
))}
</div>
);
};
CodePudding user response:
You can create an interface for each item contained in the array (let's say Icon
), then use it to properly type the iconsArr
prop as an array of that type (Icon[]
).
interface Icon {
id: string;
imgPath: string;
name: string;
}
interface Props {
iconsArr: Icon[]
}
const PrimarySkills = (props: Props) => {
return (
<div>
{props.iconsArr.map((icon) => (
<img src={icon.imgPath} alt={icon.name} key={icon.id} height='30' />
))}
</div>
);
};
Note that because you're passing iconsArr.primary
to the iconsArr
prop, iconsArr
will be an array (it won't have the primary
property). You should map through it using props.iconsArr.map(...)
instead.