MUI: either `image` or `src` property must be specified - reactjs

It's looks like CardMedia need an image while component is created. Since I am pulling the image data via componentDidMount (RestAPI) then the component is already mount.
componentDidMount() {
// get all items via category ID and owner ID
const restApi = new API({ url: 'api' })
restApi.createEntity({ name: 'items' })
// api/items/<categoryId>/<ownerId>
restApi.endpoints.items.getTwo({ id_a: this.props.categoryId, id_b: this.props.ownerId }).then(({ data }) => this.setState({ appData: data }))
}
render() {
const { classes } = this.props;
let classNameHolder = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.purpleAvatar];
this.state.appData.map(element => {
this.state.images.push(element.imageUrl);
});
return (
<Card>
<CardHeader
avatar={
<Avatar aria-label="Recipe"
className={classNameHolder[Math.floor(Math.random() * classNameHolder.length)]}>
{this.props.userName.charAt(0).toLocaleUpperCase()}
</Avatar>}
title={this.props.userName} disableTypography={true} />
<CardActionArea disabled={this.state.images.length === 1 ? true : false}>
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex]}
onClick={this.handleOnClick} />
</CardActionArea>
</Card >
);
}
}
I can move the all API one level up so I use the props in order to pass data image but I would like to know if you guys have any some elegant solution.

or you can do a simple check in the component itself so to avoid resetting the state, display a mui spinner for instance while content loads
this will fix the warning and display nice feedback to the user
<>
{imgUrl ? (
<CardMedia
component="img"
alt="Contemplative Reptile"
height="140"
src={imgUrl}
title="Contemplative Reptile"
/>
) : (
<Spinner />
)}
</>

I had also faced same problem,
I simply added a image link in image prop of <CardMedia>.
Like,
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex] || 'https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-11e8-8d89-1e61320e1d82.png'}
onClick={this.handleOnClick} />
For me it solved, by just adding a image link.

You can use the Skeleton component to display a rectangle placeholder with the same height as the image while it is being fetched:
{loading ? (
<Skeleton sx={{ height: 140 }} animation="wave" variant="rectangular" />
) : (
<CardMedia component="img" height="140" image={YOUR_IMAGE_URL} />
)}

Not sure what appData contains, but I made some changes to your code, hopefully is gonna give you a better understanding.
render() {
const { classes } = this.props;
let classNameHolder = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.purpleAvatar];
/*
// you don't save the return of the next array anywhere, so this map is doing nothing.
this.state.appData.map(element => {
// you cannot redefine state like this, to redefine state you have to use setState
this.state.images.push(element.imageUrl);
});
*/
const imagesUrl = this.state.appData.map(el => el.imageUrl);
return (
< Card >
<CardHeader
avatar={
<Avatar aria-label="Recipe"
className={classNameHolder[Math.floor(Math.random() * classNameHolder.length)]}>
{this.props.userName.charAt(0).toLocaleUpperCase()}
</Avatar>}
title={this.props.userName} disableTypography={true} />
{/* This part I don't undestand much what you try to do, I can propose use map of imagesUrl. But to help you more I need to know more info about what you try to do here */}
{/* Let's not render this part of the component instead of disabled it */}
{imagesUrl.length > 0 &&
<CardActionArea disabled={this.state.images.length === 1 ? true : false}>
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex]}
onClick={this.handleOnClick} />
</CardActionArea>
}
</Card >
);
}
}
Suggestion reviewing your array appData, maybe is good idea print the content after you retrieve it, let's see an example.
const { classes } = this.props;
const classNameHolder = [classes.redAvatar, classes.greenAvatar, classes.blueAvatar, classes.purpleAvatar];
const AvatarComponent = (
<Avatar aria-label="Recipe"
className={classNameHolder[Math.floor(Math.random() *
classNameHolder.length)]}>
{this.props.userName.charAt(0).toLocaleUpperCase()}
</Avatar>
);
return (<div className="Cards">
{this.state.appData.map(data => (
<Card>
<CardHeader avatar={AvatarComponent} title={this.props.userName} disableTypography={true} />
<CardActionArea disabled={data.imageUrl !== ''}>
<CardMedia
id={this.props.ownerId}
className={classes.media}
image={this.state.images[this.state.imageIndex]}
onClick={this.handleOnClick} />
</CardActionArea>
</Card>
))}
</div>);
Like this, we wait to get the async data before rendering the component, previously I changed, instead of disabling the component just prevent render it if you still don't have the images.

I faced with the same problem and solved it by initializing that state in the constructor. The "CardMedia" has 'image' attribute which needs to receive a String, but when you want to send a state there, something like image={this.state.images[this.state.imageIndex]}, it returns null in the first rending time. You can solve the problem by adding the below code in your constructor.
this.state = {
images: 'some default address/link/values'
};

const photos = [
"http://i.photo.cc/300?img=1",
"http://i.photo.cc/300?img=2",
"http://i.photo.cc/300?img=3",
"http://i.photo.cc/300?img=4"
];
{photos.map(photo => (
<CardMedia image={photo} />
))}
Providing image prop with the direct URL also works!

just add component="image" and your are good to go
<CardMedia component="image"/>

To get the image in the CardMedia component follow the below way:-
Import the image from any folder to the desired componnent & it will be done !
import picture from "../assets/picture.jpg"
<CardMedia
component="img"
height="20%"
image={image}
alt="scene"
/>

Related

react-infinite-scroll-component resets scroll position

I'm using react-infinite-scroll-component with Mantine's Select component, and have come across an issue. Basically whenever new data loads, the scroll bar resets all the way to the top, which as you can imagine is quite annoying in terms of UX.
Does anyone have a clue of why this is happening? While inspecting the DOM, it seems that the infinite scroll component completely re-renders for some reason.
You can see what I mean in this gif:
I'm almost sure that you are using some state for checking. I will give you a real bad example & solution for it.
Bad example which isn't works:
const hasData = !isLoading && postsResp?.content?.length;
{!hasData && (
<InfiniteScroll
dataLength={postsResp?.content?.length}
next={() => getContentFeed(true)}
hasMore={!postsResp?.last}
loader={(
<Skeleton
variant='text'
width={120}
height={24}
sx={{ margin: 'auto' }}
/>
)}
>
{postsResp?.content?.map((post: Content) => (
<Post key={`post_${post.uuid}+${Math.random()}`} post={post} />
))}
</InfiniteScroll>
) : (
'No posts'
)}
And this is a one which works good:
I know that you noticed i've moved the check if hasData on other place. I did that because each time this state is updating with new value and react re-render my component. That's why the scroll goes on top each time.
{(!hasData && !isLoading) && (
'No posts'
)}
<InfiniteScroll
dataLength={postsResp?.content?.length ?? 0}
next={() => getContentFeed(true)}
hasMore={!postsResp?.last}
loader={(
<Skeleton
variant='text'
width={120}
height={24}
sx={{ margin: 'auto' }}
/>
)}
>
{postsResp?.content?.map((post: Content) => (
<Post key={`post_${post.uuid}+${Math.random()}`} post={post} />
))}
</InfiniteScroll>
The main idea here is to remember to do not update any state according to your infinity scroll which can re-render your component.

Conditional rendering of parent component in React

I need to return either Porover or Card depending on the condition with the same children content. This can be done by taking the children content into a separate component and returning it like this:
true ? <Popover><ChildrenContent props={props}/></Popover>
: <Card><ChildrenContent props = {props}/></Card>
But it seems to me that this is not the best solution in this case
<Popover dataCy="complexValidation">
<Section marginBottom={3}>
</Section>
<Flex flexDirection="column" gap={3}>
{validations.map((validation) => (
<Flex.Item key={validation.text}>
<Flex alignItems="center">
<Icon name="check_circle" size="large" color={validation.isSuccess ? 'positive' : 'negative'} />
<Flex.Item>
<Typography variant="bodyText2" component="span">
{validation.text}
</Typography>
</Flex.Item>
</Flex>
</Flex.Item>
))}
</Flex>
</Popover>

Pass icon button as props using react

I have a common grid component where I define the structure of the grid and also structure of a button bar that goes on top of the grid.
Common-grid.js
<Box height='100%' width='100%' position='absolute'>
<div className="common-grid">
<div className="button-bar">
</div>
<div className="ag-grid">
</div>
</div>
</Box>
I pass data to the grid from my other component based to fill in the grid.
MyComponent.js
{gridData.length > 0 && <Grid tableData={gridData} columnData={activeListColumnDef} {...props}/>}
Along with the data, I would also like to pass icon buttons that I would like to see in button bar.
<IconButton
icon={<AddIcon />}
onClick={onClickOpenActiveListEditor}
/>
<IconButton
icon={<EditIcon />}
/>
I do not want to define icon buttons in the common component but pass it as props. Is it possible to pass such html elements along with its event listeners as props? Please help!
Sure, it's called a render prop. Just directly pass the node like this:
// in the parent component
<Grid
tableData={gridData}
columnData={activeListColumnDef}
icon={<AddIcon onClick={onClickOpenActiveListEditor} />}
{...props}
/>
// in the Grid component
function Grid({tableData, columnData, icon}){
return (
<>
// grid stuff
{icon && icon}
</>
)
}
If you need typescript support, the node would typed as such:
interface GridProps{
// stuff
icon?: React.ReactNode;
}
You could do something like:
const renderIcon = (onClick) => {
return <Icon onClick={onClick} />
}
...
<IconButton renderIcon={renderIcon} />
Then, inside IconButton:
{renderIcon()}

Is there a way to use <Collapse> as my Transition component while using the <Popper> component to display a Menu onHover?

The following question is regarding React and Material-UI:
I am trying to use the <Collapse> transition component when displaying my <Menu> onMouseEnter. However, there seems to be an issue in the Material-UI library when it comes to the way the <Collapse> component and the <Popper> / <Popover> component. The issue is currently open and can be seen here.
Has anyone found a good workaround for this? Basically, I am just hoping to have a subnav Menu appear when you hover over a link with this specific transition.
I have tried using the <Grow> component and the transition works just fine, but we specifically are trying to use the <Collapse> transition.
export const NavBarItem = ({ navItem }) => {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const anchorRef = React.useRef(null);
function handleToggle() {
setOpen(prevOpen => !prevOpen);
}
function handleClose(event) {
if (anchorRef.current && anchorRef.current.contains(event.target)) {
return;
}
setOpen(false);
}
return (
<React.Fragment>
<Link className={classes.link} href={BASE_HOMEPAGE + navItem.path}>
<Typography
className={classes.title}
ref={anchorRef}
aria-controls="menu-list-grow"
aria-haspopup="true"
onMouseEnter={handleToggle}
onMouseLeave={handleToggle}
>
{navItem.title}
</Typography>
</Link>
<Popper
open={open}
anchorEl={anchorRef.current}
onMouseEnter={handleToggle}
onMouseLeave={handleToggle}
transition
disablePortal
placement="bottom-start"
>
<Collapse in={open}>
<Paper id="menu-list-grow">
<ClickAwayListener onClickAway={handleClose}>
<MenuList className={classes.paperMenu}>
{navItem.menuItems.map(item => (
<Link
className={classes.link}
href={
item.external ? item.path : BASE_HOMEPAGE + item.path
}
>
<MenuItem
className={classes.paperMenuItem}
onClick={handleClose}
>
{item.text}
</MenuItem>
</Link>
))}
</MenuList>
</ClickAwayListener>
</Paper>
</Collapse>
</Popper>
</React.Fragment>
);
};
The code shown above is for a specific NavItem in a NavComponent. It is essentially just a dropdown component to show a subnav when you hover over a specific link.
Thank you for your help and please let me know if you need anymore additional information.
You can try to use the TransitionProps given by the Popper when using the transition props, as shown in the documentation
<Popper id={id} open={open} anchorEl={anchorEl} transition>
{({ TransitionProps }) => (
<Fade {...TransitionProps} timeout={350}>
<div className={classes.paper}>The content of the Popper.</div>
</Fade>
)}
</Popper>
For smoother UI you can also use the keepMounted property in Popper:
<Popper id={id} open={open} anchorEl={anchorEl} transition keepMounted>

Google map does not shrink when user opens sidebar

I am new to both React and Grommet and have worked through the getting started tutorial. When I add a google map to the main container it renders and fills the whole screen. However, when I click the notification icon to load the sidebar it only renders in a tiny column on the side. Is there a way for me to edit the style to adjust the width automatically or do I need to have the container width as a property that changes when the button is clicked? (Please excuse any question format errors as this is my first post.)
I have tried looking through the Grommet box props and various CSS style settings without success.
App.js:
const { showSidebar } = this.state;
return (
<Grommet theme={theme} full>
<ResponsiveContext.Consumer>
{size => (
...
<Box direction='row' flex overflow={{ horizontal: 'hidden' }}>
<Box
align='start'
justify='start'
fill='horizontal'
responsive='true'
>
<MapContainer />
</Box>
{!showSidebar || size !== 'small' ? (
<Collapsible direction='horizontal' open={showSidebar}>
<Box
flex
width='medium'
background='light-2'
elevation='small'
align='center'
justify='center'
>
sidebar
</Box>
</Collapsible>
) : (
...
}
</Box>
</Box>
)}
</ResponsiveContext.Consumer>
</Grommet>
);
MapContainer.js:
return (
<Map google={this.props.google} zoom={14}/>
);
I would like the map to shrink to fill the container/the container to shrink when the sidebar loads.

Resources