Simone
Simone

Reputation: 1337

React JSS and TypeScript

I've been using React for a while, and now I want to switch to using React with TypeScript. However, I've grown used to JSS styles (via the react-jss package), and I can't understand how I'm supposed to use them with TypeScript. I also use the classnames package, to assign multiple class names conditionally, and I get TypeSCript errors for that.

Here is my React component template:

import React, { Component } from 'react';
import withStyles from 'react-jss';
import classNames from 'classnames';

const styles = theme => ({
});

class MyClass extends Component {
    render() {
        const { classes, className } = this.props;
        return (
            <div className={classNames({ [classes.root]: true, [className]: className})}>
            </div>
        );
    }
};

export default withStyles(styles)(MyClass);

I'm just learning TypeScript, so I'm not sure I even understand the errors I get. How would I write something like the above in TypeScript?

UPDATE

Here is how I finally converted my template:

import React from 'react';
import withStyles, { WithStylesProps }  from 'react-jss';
import classNames from 'classnames';

const styles = (theme: any) => ({
    root: {
    },
});

interface Props extends WithStylesProps<typeof styles> {
    className?: string,
}

interface State {
}

class Header extends React.Component<Props, State> {
    render() {
        const { classes, className } = this.props;
        return (
            <div className={classNames({ [classes.root as string]: true, [className as string]: className})}>
            </div>
        );
    }
};

export default withStyles(styles)(Header);

Things to keep in mind:

Upvotes: 6

Views: 5229

Answers (1)

Lowkey
Lowkey

Reputation: 836

With TypeScript, you'll need to define your props as shown in here. It is also recommended to use function component if your React component only need render method

For your case, the code should look like this:

import React from 'react';
import withStyles, { WithStyles } from 'react-jss';
import classNames from 'classnames';

const styles = theme => ({
  root: {

  }
});

interface IMyClassProps extends WithStyles<typeof styles> {
  className: string;
}

const MyClass: React.FunctionComponent<IMyClassProps> = (props) => {

    const { classes, className } = props;
    return (
        <div className={classNames({ [classes.root]: true, [className]: className})}>
        </div>
    );
};

export default withStyles(styles)(MyClass);

Upvotes: 1

Related Questions