How can I pass post.mainImage
to backgroundImage
style.
Here is my code;
import React from 'react';
import { Post } from '../interfaces';
import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';
type Props = {
post: Post;
}
const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
createStyles({
root: {
maxWidth: '100%',
backgroundImage: ({ post }) => post.mainImage
},
date: {
margin: theme.spacing(1),
marginLeft: theme.spacing(2)
},
heroimage: {
maxWidth: '100%',
height: 'auto',
objectFit: 'cover'
}
})
);
export default function HeroPost({ post }: Props) {
const classes = useStyles({ post });
return (
<Container className={classes.root}>
<img alt={post.title} src={post.mainImage} className={classes.heroimage} />
</Container>
);
}
The code below has passed without a problem from the linter. But still cannot get the backgroundImage
value on the front.
You can supply type variables to the call to makeStyles
(note that the first one must be the theme type and the second the prop type):
type Props = {
post: Post;
};
const useStyles = makeStyles<Theme, Props>(theme =>
createStyles({
root: {
maxWidth: '100%',
backgroundImage: ({ post }) => `url("${post.mainImage}")`
},
// ...
})
);
export default function HeroPost({ post }: Props) {
const classes = useStyles({ post });
return (
// ...
);
}
You need to pass props with its type directly where you want to access it. This Should work fine.
type BgProps = {
mainImage: string;
}
const useStyles = makeStyles<Theme, Props>((theme: Theme) =>
createStyles({
root: {
maxWidth: '100%',
backgroundImage: (props: BgProps) => props.mainImage
},
date: {
margin: theme.spacing(1),
marginLeft: theme.spacing(2)
}
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With