Creating custom designs for Material UI components

Although not a major issue, there is something that bothers me. I am currently using react, typescript, and css modules along with . The problem arises when styling material ui components as I find myself needing to use !important quite frequently. Is there a way to create styles without relying on important? I have created a sample project to showcase this issue: https://github.com/halkar/test-css-modules

Answer №1

material-ui offers a variety of components for styling, and there are two approaches to achieving this.

Implement Global Styles

One way is to define styles globally and apply them to the theme. Here's an example taken from the documentation http://www.material-ui.com/#/customization/themes:

import React from 'react';
import {cyan500} from 'material-ui/styles/colors';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AppBar from 'material-ui/AppBar';

const muiTheme = getMuiTheme({
  palette: {
    textColor: cyan500,
  },
  appBar: {
    height: 50,
  },
});

class Main extends React.Component {
  render() {
    return (
      <MuiThemeProvider muiTheme={muiTheme}>
        <AppBar title="My AppBar" />
      </MuiThemeProvider>
    );
  }
}

export default Main;

In the above example, the AppBar component has a height of 50px, which means every instance of the AppBar component will have that height when styled with the muiTheme. You can find a list of available styles for each component here.

Utilize Style Attribute for Component Styles

For individual component styling, you can use the style attribute to pass specific styles.

Here's another example from the documentation where a margin of 12px is applied to a RaisedButton:

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const style = {
  margin: 12,
};

const RaisedButtonExampleSimple = () => (
  <div>
    <RaisedButton label="Default" style={style} />
    <RaisedButton label="Primary" primary={true} style={style} />
    <RaisedButton label="Secondary" secondary={true} style={style} />
    <RaisedButton label="Disabled" disabled={true} style={style} />
    <br />
    <br />
    <RaisedButton label="Full width" fullWidth={true} />
  </div>
);

export default RaisedButtonExampleSimple;

You can define styles in the same file or import them from a separate file for component usage.

If you need to apply multiple styles, you can use the spread operator like so: style={{...style1,...style2}}. Make sure to check the component properties for available style options to customize different parts of the component.

Refer to the component properties and global style properties for styling guidance. This should assist you in applying the desired styles effectively!

Answer №2

In order to properly manage the styling of my components, I realized that using JssProvider would be essential. By instructing it to place Material UI styles before mine in the head section, I can ensure a consistent look and feel throughout the application.

import JssProvider from 'react-jss/lib/JssProvider';
import { create } from 'jss';
import { createGenerateClassName, jssPreset } from 'material-ui/styles';

const generateClassName = createGenerateClassName();
const jss = create(jssPreset());
// To establish a custom insertion point for injecting styles into the DOM,
jss.options.insertionPoint = document.getElementById('jss-insertion-point');

function App() {
  return (
    <JssProvider jss={jss} generateClassName={generateClassName}>
      ...
    </JssProvider>
  );
}

export default App;

Answer №3

It is necessary to utilize the component API's in order to apply styles to imported components from libraries using CSS, especially if the component has specific API's for styling.

*Update

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

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

function Classes(props) {
  return (
    <Button
      classes={{
        root: props.classes.root, // class name, e.g. `classes-root-x`
        label: props.classes.label, // class name, e.g. `classes-label-x`
      }}
    >
      {props.children ? props.children : 'classes'}
    </Button>
  );
}

Classes.propTypes = {
  children: PropTypes.node,
  classes: PropTypes.object.isRequired,
};

export default withStyles(styles)(Classes);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Leveraging the power of useEffect in Next.js to interact with the window object

I encountered an issue when trying to access window.localStorage in my Next.js application. Since Next.js allows for both server-side and client-side rendering, I ran into an error when attempting to set the default value of a state using local storage lik ...

Encountering a Typescript issue stating "Property 'then' does not exist" while attempting to chain promises using promise-middleware and thunk

Currently, I am utilizing redux-promise-middleware alongside redux-thunk to effectively chain my promises: import { Dispatch } from 'redux'; class Actions { private static _dispatcher: Dispatch<any>; public static get dispatcher() ...

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

Exploring abstract classes for diverse implementation strategies?

Consider the following scenario: export abstract class Button { constructor(public config: IButton) {} abstract click(); } Now, we have a concrete class: class ButtonShowMap extends Button { private isShow = false; constructor(public config: IBu ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Is There a Comparable Feature to *ngIf in DevExtreme?

Currently, I am diving into the world of webapp development using DevExtreme. As a novice in coding, this is my first time exploring the functionalities of DevExtreme. Essentially, I am seeking guidance on how to display certain elements based on specific ...

Strategies for modifying the title attribute within an <a> tag upon Angular click event

I am attempting to dynamically change the title attribute within an anchor tag upon clicking it. The goal is for the title attribute to toggle between two states each time it is clicked. Currently, I am able to change the title attribute successfully upon ...

What is the solution for fixing scrolling while keeping the header fixed and ensuring that the widths of headers and cells are equal?

Is there a way to set a minimum width for headers in a table and provide a scroll option if the total width exceeds 100% of the table width? Additionally, how can we ensure that the width of the header and td elements are equal? Below is the HTML code: ht ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Having Trouble Styling Radio Buttons with CSS

Hello, I'm facing an issue with hiding the radio button and replacing it with an image. I was successful in doing this for one set of radio buttons, but the second set in another row is not working properly. Additionally, when a radio button from the ...

Tips for minimizing API calls when validating the authenticity of a JWT token stored in a cookie

Upon a user logging in through my React frontend, an API call is made to the server side to generate a JWT token which is then sent back in a secure HTTP-only cookie. Subsequent API calls from the frontend include this cookie for verification on the server ...

Tips for uploading images, like photos, to an iOS application using Appium

I am a beginner in the world of appium automation. Currently, I am attempting to automate an iOS native app using the following stack: appium-webdriverio-javascript-jasmine. Here is some information about my environment: Appium Desktop APP version (or ...

Ways to troubleshoot errors that arise while building Next.js with Mui framework

After running npm install @mui/material @emotion/react @emotion/server, I encountered an error while trying to build my Next.js app during linting and type checking. info - Linting and checking validity of types ...Failed to compile. ./node_modules/@mui/ ...

Deactivate any days occurring prior to or following the specified dates

I need assistance restricting the user to choose dates within a specific range using react day picker. Dates outside this range should be disabled to prevent selection. Below is my DateRange component that receives date values as strings like 2022-07-15 th ...

Understanding how to leverage styles.module.scss for implementing personalized styling within react-big-calendar

I'm currently working with the react-big-calendar library in order to develop a customized calendar. However, I've encountered an issue where the SCSS styling is not being applied correctly. export const JobnsCalendar = () => ( <Calendar ...

Column-oriented and Slim-fit packaging

I have been working on designing a layout with a fixed height that will display multiple columns of specified size to accommodate flowing text. While I have successfully implemented this, I am facing an issue where the enclosing div does not adjust its siz ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...

Customize the border style for the span element

I attempted to use the code below in JavaScript/jQuery to adjust the border thickness. Unfortunately, it seems to be ineffective. Can someone please assist me? //$("span").css({"border":"4px solid green"}); document.getElementById("192.168.42.151:8984_ ...