I am running HorizontallScrollbar component by passing data as a prop. Whenever I run HorizontalScrollbar component then following error coming in console tab of Chrome:
Error:
Uncaught TypeError: data.map is not a function
HorizontalScrollbar.js
import React from 'react';
import {Box} from '@mui/material';
const HorizontalScrollbar = ({data}) => {
return (
<div>
{data.map((item) => (
<Box
key = {item.id || item}
itemId = {item.id || item}
title = {item.id || item}
m = "0 40px"
>
{item}
</Box>
)
)
}
</div>
)
}
export default HorizontalScrollbar;
Passing data as a Prop:
<Box sx = {{position: "relative", width: "100%", p: "20px"}}>
<HorizontalScrollbar data = {bodyParts} />
</Box>
How is bodyParts instantiated? Is it a state? If it is it should default to an empty array []
Or you could add a check before mapping through. I added an Array.isArray() check before invoking the map() function as it is only for Arrays.
Additional Info
It could be that data is not yet populated due to waiting for an API call to complete or some other reason. In this case my fix would simply render an empty div during first render due to the check and prevent the console error. During next render when the data is ready the data in this case would be a proper Array type, the check would pass (Array.isArray(data)) and the items would render the Box component properly.
import React from 'react';
import {Box} from '@mui/material';
const HorizontalScrollbar = ({data}) => {
return (
<div>
{Array.isArray(data) && data.map((item) => (
<Box
key = {item.id || item}
itemId = {item.id || item}
title = {item.id || item}
m = "0 40px"
>
{item}
</Box>
)
)
}
</div>
)
}
export default HorizontalScrollbar;
I think using the double ampersand && gives it an option.
That is, if API had not been called, remain empty for the time being