0

I'm struggling to get material-ui's theming to work with react-router-dom in Typescript. When accessing classes.root in render(), I get TypeError: Cannot read property 'root' of undefined, but I can't figure out how I'm merging/passing props incorrectly. Can anyone see what I'm doing wrong? Many thanks in advance.

Relevant code below:

const styles = (theme: Theme) =>
  createStyles({
    root: {
      maxWidth: 345,
    },
  });

interface HomeProps extends RouteComponentProps, WithStyles<typeof styles> {
  classes: any;
}

export class Home extends React.Component<HomeProps, HomeState> {
  constructor(props: HomeProps) {
    super(props);
  }
  render() {
    const { classes } = this.props;
    //  classes.root is undefined...
  }
}

export default withRouter(withStyles(styles)(Home));

Edit to add: the answer to this question did not resolve this issue: Typescript error when using withRouter(withStyles(styles)(ComponentName))

1 Answer 1

0

There was some syntax errors in the code maybe it is the cause. WithStyles<typeof styles> gives this.props.classes its type, you don't need nor should override it with classes: any;.

This works for me

const styles = (theme: Theme) =>
  createStyles({
    root: {
      maxWidth: 345,
    },
  });

interface HomeProps extends RouteComponentProps, WithStyles<typeof styles> {}

type HomeState = any;

export class Home extends React.Component<HomeProps, HomeState> {
  // constructor(props: HomeProps) {
  //   super(props);
  // }
  render() {
    const { classes } = this.props;
    return <div className={classes.root}></div>
  }
}
autocompletion completes `classes.root`

https://codesandbox.io/s/zealous-kalam-u3mhx?file=/Home.tsx

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer, unfortunately this still results in the same error (TypeError: Cannot read property 'root' of undefined)
Can you reproduce the issue with a codesandbox? Because I don't see the error in mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.