Material ui v4: I want to customize a Material UI button inside a class component using types script. Kindly let me know how can I do it?

Viewed 580
const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
  },
};
function HigherOrderComponent(props) {
  const { classes } = props;
  return <Button className={classes.root}>Higher-order component</Button>;
}

HigherOrderComponent.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(HigherOrderComponent);

above code from https://mui.com/styles/basics/#higher-order-component-api I am unable to convert into a class Component

1 Answers

You can use makeStyles for this.

const useStyles = makeStyles({
    root: {
        background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
        border: 0,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        padding: '0 30px',
    },
});

export default function HigherOrderComponent() {
    const classes = useStyles();
    return <Button className={classes.root}>Higher-order component</Button>;
}

Also see the documentation about makeStyles for more information: https://mui.com/styles/advanced/#overriding-styles-classes-prop


Edit: If you want to use a class component, you could use createStyles in combination with withStyles.

import { Button, createStyles, WithStyles, withStyles } from '@material-ui/core';
import React, { PureComponent } from 'react';

const styles = createStyles({
    root: {
        background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
        border: 0,
        borderRadius: 3,
        boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
        color: 'white',
        height: 48,
        padding: '0 30px',
    },
});

type PropsType = WithStyles<typeof styles>;

export class HigherOrderComponent extends PureComponent<PropsType> {
    constructor(props: PropsType) {
        super(props);
    }

    render() {
        return <Button className={this.props.classes.root}>Higher-order component</Button>;
    }
}

export default withStyles(styles)(HigherOrderComponent);
Related