Reputation: 11
I have an array of string arrays like, items : [a[],b[],c[],d[]].
I want to render the elements of this array as a carousel using React. The following code doesn't work. Any help would be appreciated.
public render(): React.ReactElement<IReactCarouselProps> {
return (
<div>
<Carousel>
{this.state.items.map((list,key) => {
return(
<div key = 'key'>
<div>{list.a}</div>
</div>
);
}
)}
</Carousel>
</div>
);
}
Upvotes: 1
Views: 3414
Reputation: 2510
working example https://jsfiddle.net/shuts13/cfLxrn15/6/
render() {
return (
<div>
{this.state.items.map((subArray, index) => {
return (
<div key={index}>
{subArray.map((subitem, i) => {
return (
<ul>
<li>{subitem.value}</li>
</ul>
);
})}
</div>
);
})}
</div>
);
}
Upvotes: 4
Reputation: 432
To render a array of arrays you can map the second array too. This way your code will loop the parent array and loop all the child arrays, rendering them the way you want.
Here is a example:
public render(): React.ReactElement {
const flatArray = parentArray.map(
(childArray) => {(childArray.map((childElement) => <div>Your code here</div>)})
);
return (
{flatArray}
);
}
or, even better, you can use array flat.function(), like this:
public render(): React.ReactElement {
const flatArray = parentArray.flat().map((childElement) => <div>Your code here</div>)
return (
{flatArray}
);
}
Read more about array.flat() method here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/flat
Upvotes: 1