dommer
dommer

Reputation: 19810

How do I style a Material UI 1.x FormLabelControl's label?

I'm trying to create a labeled checkbox control in Material UI (1.4.1) where I can style the label text (size, color, weight, etc).

Here's what I've come up with---which works

import React from 'react';
import {withStyles} from '@material-ui/core/styles';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';

const LabeledCheckbox = props => {
    const unstyled = props => (
        <FormControlLabel
            control={
                <Checkbox/>
            }
            label={props.label}
            classes={{
                label: props.classes.label
            }}
        />
    );

    const Styled = withStyles({
        label: props.labelStyle || {}
    })(unstyled);

    return (<Styled label={props.label}/>);
};

export default LabeledCheckbox;

Usage is:

<LabeledCheckbox label='So is this' labelStyle={{ fontWeight: 'bold' }}/>

However, this feels like I'm really making a meal of it. Surely there's a much easier way to style the FontControlLabel text. I feel like I don't have the correct mental model of how Material UI styling works.

Can anyone tell me how this code should be written?

Upvotes: 1

Views: 6142

Answers (1)

Luke Peavey
Luke Peavey

Reputation: 3879

You can use the classes API to inject custom styles each time you use a component.

// Define custom default styles for checkbox label (optional)
const styles = {
  label: {}
};

function LabeledCheckbox({ label, classes, ...CheckboxProps }) {
  return (
    <FormControlLabel
      label={label}
      classes={classes}
      control={<Checkbox {...CheckboxProps} />}
    />
  );
}

export default withStyles(styles)(LabeledCheckbox);

Usage:

const styles = theme => ({
  checkboxLabelA: {
    fontWeight: 800,
  },
  checkboxLabelB: {
    color: 'blue'
  }
});

class MyForm extends React.Component {
  render() {
    const { classes } = this.props;
    return (
      <FormGroup>
        <LabeledCheckBox
          label="Checkbox A"
          classes={{ label: classes.checkboxLabelA }}
        />
        <LabeledCheckBox
          label="Checkbox B"
          classes={{ label: classes.checkboxLabelB }}
        />
      </FormGroup>
    );
  }
}

export default withStyles(styles)(MyForm);

Live example on CodeSandbox

Upvotes: 2

Related Questions