Hongli Bu
Hongli Bu

Reputation: 561

Material-UI: Property 'X' does not exist on type '{}' when passing props to makestyles in React

I am now trying to use Adapting based on props https://material-ui.com/styles/basics/#adapting-based-on-props

import React from 'react';
import { makeStyles } from '@material-ui/core';

const useStyles = makeStyles({
    // style rule
    foo: props => ({
        (Error!)
        backgroundColor: props.backgroundColor,
    }),
    bar: {
        // CSS property(Error!)
        color: props => props.color,
    },
});

function MyComponent() {
    // Simulated props for the purpose of the example
    const props = { backgroundColor: 'black', color: 'white' };
    // Pass the props as the first argument of useStyles()
    const classes = useStyles(props);

    return <div className={`${classes.foo} ${classes.bar}`} />
}
export default MyComponent;

but I got the error TS2339: Property 'X' does not exist on type '{}' when passing props

so what happened here? how to fix it?

enter image description here

Upvotes: 1

Views: 3391

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81380

The second generic argument of makeStyles is the props type, by default is {}. You can override it like this:

import { DefaultTheme } from "@material-ui/styles";

const useStyles = makeStyles<DefaultTheme, Props>(...)

Full working code:

import { makeStyles } from "@material-ui/core/styles";
import { DefaultTheme } from '@material-ui/styles';

interface Props {
  color: 'red' | 'blue';
}

// you only need to set the type of props once here
const useStyles = makeStyles<DefaultTheme, Props>({
  root: {
    // props now has Props type
    background: (props) =>
      props.color === 'red'
        ? 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)'
        : 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
    border: 0,
    borderRadius: 3,
    // so is this props
    boxShadow: (props) =>
      props.color === 'red'
        ? '0 3px 5px 2px rgba(255, 105, 135, .3)'
        : '0 3px 5px 2px rgba(33, 203, 243, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
    margin: 8,
  },
});

Live Demo

Edit 67275984/ts2339-property-x-does-not-exist-on-type-when-passing-props-to-makestyle

Upvotes: 1

Viet
Viet

Reputation: 12787

You receive this error because you are using typescript. So if you want fix, you need to define an interface/type:

interface PropsStyle {
  backgroundColor: string;
  color: string;
}

const useStyles = makeStyles({
  // style rule
  foo: (props: PropsStyle) => ({
    backgroundColor: props.backgroundColor,
  }),
  bar: {
    color: (props: PropsStyle) => props.color,
  },
});

Upvotes: 1

Related Questions