简体   繁体   中英

How do I use material-ui themed error style (color) for non-form text

The docs are clear on using error styles for form inputs such as text fields. But how do I use the same style on a custom element such as a text label for a file upload button , or any other custom component that might not fit the a pre-defined component?

Edit for clarity: I don't want to just choose a color I like and plop it in my css with an appropriate selector. I want to make sure I'm using the same error color as the theme, whether that's the default, some imported theme, or custom (if custom it's pretty easy, but not DRY, to just use the same value in css).

Specifically, in this use case, I want to limit users to uploading files less than 100MB, and display an error message if they have selected a file larger than this limit. I'd like to display the text in the error style of the configured theme, but from the material-ui docs I can only see how to set error properties of pre-packaged components such as text fields.

So here I have, simplified:

      <input
        accept="video/*"
        id="file-upload-button"
        type="file"
        onChange={(e) => {this.fileChanged(e);}}
      />
      <label htmlFor="file-upload-button">
        <Button variant="contained" component="span" color="default">
          Browse video
        </Button>
        <br /><small>(Max size: 100MB)</small>
      </label>

where the input tag has display: none applied via a css file. Also,

  fileChanged(e) {
    let file = e.target.files[0];
    let sizeMB = file.size / 2**20;
    this.setState({
      selectedFile: e.target.files[0],
      fileTooLarge: sizeMB > 100
    });
  }

How do I get the theme's error color to apply it to the "Max Size" message or other element?

3 steps to solve your issue:

  1. You have to inject the theme into your app with the theme provider (apply to v3 MUI, but should be similar with v4 now). See doc .

  2. You can then customize the theme, like such:

const theme = createMuiTheme({
  palette: {
    error: {
      main: "#ff604f"
    }
  }
}
  1. Finally you can use your custom color by injecting styles into your component with withStyles() (or useStyles() in v4 hook for instance) and create your styles const in your component, example:
const styles = theme => ({
  button: {
    backgroundColor: theme.palette.error.main,
  }
}

Note: using error as a palette variable name will override the default error color value.

Possible duplicate of: How to add a class with React.js?

You could give an ID and then: getElementById.classList.add("errorClass");

Then if the user uploads the proper size: getElementById.classList.remove("errorClass");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM