I am trying to map over an array of objects received from the Unsplash API. I have read a bit about indexers in TypeScript but i am not sure i understand it completely. I have a stateless React component which receives a prop of state from parent. The value is a array of object. (see example from unsplash API). How do i define the shape of the object received from the API?
My code:
interface IProps {
images: [{}];
}
interface IIMageUrls {
image: {
urls: { regular: string}
}
[index: string]: any;
}
export default class ImageList extends React.Component<IProps, {}> {
constructor(props: IProps) {
super(props);
}
render() {
this.props.images.map((image: IIMageUrls) => {
return <img src={image.urls.regular} />
});
}
}
Example of the unsplash JSON:
{
"results": [
"urls": {
"raw": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f",
"full": "https://hd.unsplash.com/photo-1416339306562-f3d12fefd36f",
"regular": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=1080&fit=max&s=92f3e02f63678acc8416d044e189f515",
"small": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&s=263af33585f9d32af39d165b000845eb",
"thumb": "https://images.unsplash.com/photo-1416339306562-f3d12fefd36f?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=200&fit=max&s=8aae34cf35df31a592f0bef16e6342ef"
}
]
}
Solution/Final Code:
interface IImageUrls {
[index: string]: string;
regular: string;
}
interface IImage {
urls: IImageUrls;
}
interface IProps {
images: Array<IImage>;
}
export default class ImageList extends React.Component<IProps, {}> {
constructor(props: IProps) {
super(props);
}
render() {
const images = this.props.images.map((image, index) => {
return <img src={image.urls.regular} key={index} />;
});
return images;
}
}
resultarray?