Use Class Component in React Material UI Mar 3rd 2020 Words: 328

Material UI is a fascinating library for react, but all its default examples are written use function component rather than class component.

Convert a component from function to class is quite easy.

Take the following Card as example.

The original code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles({
root: {
minWidth: 275,
}
title: {
fontSize: 14,
}
});

export default function SimpleCard() {
const classes = useStyles();

return (
<Card className={classes.root}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
Word of the Day
</Typography>
</CardContent>
</Card>
);
}

Converted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React from 'react';
import PropTypes from 'prop-types';
import { withStyle } from '@material-ui/core/styles'; // use withStyle instead of makeStyle
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';

// no more makeStyle
const styles = theme => ({
root: {
minWidth: 275,
margin: theme.spacing(1) // Use theme
}
title: {
fontSize: 14,
margin: props => (props.titleMargin) // This is how you use props in style
}
});

class MyCard extends React.Component {
// define props type
static propTypes = {
titleMargin: PropTypes.string
};

// define default props
static defaultProps = {
titleMargin: '10px'
};

render() {
const {classes} = this.props; // for class name referring
return (
<Card className={classes.root}>
<CardContent>
<Typography className={classes.title} color="textSecondary" gutterBottom>
Word of the Day
</Typography>
</CardContent>
</Card>
);
}
}

export default withStyle(styles)(MyCard); // Wrap use withStyle

EOF