Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing props to the makeStyle in TS

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.

like image 862
thiras Avatar asked Sep 05 '20 23:09

thiras


2 Answers

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 (
    // ...
  );
}
like image 87
Lionel Rowe Avatar answered Oct 22 '22 20:10

Lionel Rowe


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)
    }
  })
);
like image 3
anandshandilya Avatar answered Oct 22 '22 20:10

anandshandilya