Naiad
Naiad

Reputation: 63

What is the idiomatic way to do styling in Material-UI?

There are a few ways to do styling in Material-UI.

  1. Use makeStyles:
import Box from '@material-ui/core/Box'
const useStyles = makeStyles(theme => ({
  testStyled: (props: isBoolean) => ({
    width: props ? '1px' : '2px',
  })
}))

<Box className={useStyles(true).root}></Box>
  1. Use MuiBoxProps:
import Box, { MuiBoxProps } from '@material-ui/core/Box'
let isTrue = true
let props: MuiBoxProps  = {
    style: {
        marginBottom: isTrue ? '1px' : '2px'
    }
}
<Box {...props}></Box>

In the second way, I can put a special input for each individual component. For example:

let props: MuiBoxProps = {
   mb: '1px'
}

Type inference can be used to see compilation errors.

However, this method is not applicable to makeStyles because its return type is always CSSProperties.

In the first case, however, I can style them internally by adding props.

So, in conclusion:

  1. Type inference is impossible for a specific component. Can apply props in batch.

  2. Type inference is possible for a specific component. Can't apply props in batch.

What is the official recommendation?

Upvotes: 2

Views: 491

Answers (1)

Vijay  Gehlot
Vijay Gehlot

Reputation: 80

Actually, doesn't matter which way you are choosing because both the have in official documents. the matter is that in which method or way you are comfortable with.

But Yes, I think the best way is withSyles which is also I use in my professional development code.

Here is the Example:

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

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);

Upvotes: 1

Related Questions