Using multiple CSS rule names with the styled API in Material UI - reactjs

I'm using Material UI and I want to style a component using multiple rule names with the styled API.
Let's say I want to style the FormLabel Component in blue with the asterisk (required) in red.
With the Hook API I would do something like that:
import React from 'react'
import { makeStyles } from '#material-ui/core/styles'
import MuiFormLabel from '#material-ui/core/FormLabel'
const useStyle = makeStyles({
root: {
color: 'blue'
},
asterisk: {
color: 'red'
},
})
const FormLabel = ({ children }) => {
const classes = useStyle()
return (
<MuiFormLabel
classes={{
root: classes.root,
asterisk: classes.asterisk
}}
>
{children}
</MuiFormLabel>
)
}
Can I pass root AND asterisk to my component using the styled API?
I tried this but it doesn't work
import React from 'react'
import { styled } from '#material-ui/core/styles'
import MuiFormLabel from '#material-ui/core/FormLabel'
const StyledFormLabel = styled(MuiFormLabel)({
'.MuiFormLabel-root': {
color: 'blue'
},
'.MuiFormLabel-asterisk': {
color: 'red'
},
})
const FormLabel = ({ children }) => (
<StyledFormLabel>{children}</StyledFormLabel>
)

Below is an example of the correct syntax. By default, the top-level keys in the object passed to styled are assumed to be CSS property names. By adding & at the beginning of the key, it lets styled know that you are defining a nested rule. .MuiFormLabel-root is unnecessary since the root level is where properties will be applied by default (e.g. color: "blue" in the example below). The & is a reference to the root-level class, so & .MuiFormLabel-asterisk targets descendant elements with the MuiFormLabel-asterisk class.
import React from "react";
import { styled } from "#material-ui/core/styles";
import MuiFormLabel from "#material-ui/core/FormLabel";
const StyledFormLabel = styled(MuiFormLabel)({
color: "blue",
"&.Mui-error": {
color: "purple"
},
"& .MuiFormLabel-asterisk": {
color: "green"
},
"& .MuiFormLabel-asterisk.Mui-error": {
color: "red"
}
});
const FormLabel = ({ children }) => (
<>
<StyledFormLabel required>{children}</StyledFormLabel>
<br />
<StyledFormLabel error required>
{children}
</StyledFormLabel>
</>
);
export default FormLabel;

Related

how to do Storybook React Material UI custom styling

Hello I'm new to stroybook and and would liek to use custom colors on my component but i keep on getting errors.
This is the code below, could sb help me to fix this so I can see how to use storybook material ui elements in storybook..
the code:
import "bootstrap/dist/css/bootstrap.min.css";
import React from "react";
import { deepOrange, deepPurple } from '#material-ui/core/colors';
import { makeStyles } from '#material-ui/core/styles';
import Avatar from '#material-ui/core/Avatar';
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
'& > *': {
margin: theme.spacing(1),
},
},
orange: {
color: theme.palette.getContrastText(deepOrange[500]),
backgroundColor: deepOrange[500],
},
purple: {
color: theme.palette.getContrastText(deepPurple[500]),
backgroundColor: deepPurple[500],
},
}));
And this is the error.
export default {
const classes = useStyles();
title: "Components/Avatar/Number",
component: Avatar
}
export const _Avatar = () => (
<>
<Avatar>H</Avatar>
<Avatar className={classes.orange}>N</Avatar>
<Avatar className={classes.purple}>OP</Avatar>
</>
);
ERROR in
src\stories\Avatars\avatar.stories.js
Parsing error: Unexpected keyword 'const'.
export default {
const classes = useStyles();
^
title: "Components/Avatar/Number",
component: Avatar
}
It is syntactically incorrect to use the const keyword and the = operator inside your default export object. Try the following code instead:
export default {
classes: useStyles(),
title: "Components/Avatar/Number",
component: Avatar
}

Centering the placeholder for a Textfield MUI

I am trying to align a Placeholder to be centered within the Text-Field. Is there a way to do this? applying text-align: center to the input is not centering the placeholder.
You can use the &::placeholder pseudoselector on input classname like below
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import TextField from "#material-ui/core/TextField";
const useStyles = makeStyles(theme => ({
input: {
"&::placeholder": {
color: "red",
textAlign: "center"
}
}
}));
export default function Inputs() {
const classes = useStyles();
return (
<TextField
placeholder="Placeholder"
InputProps={{ classes: { input: classes.input } }}
/>
);
}
A working sandbox project link

Global Styles with React and MUI

I'm new to React and MUI but I have to write an enterprise application with a nice styling. I would like to use some kind of global styles for my application (to be able to change it later on
) with functional components in react (maybe I will later add redux).
What's the best practice approach for global styles with react and material (latest versions)?
What about this one (ThemeProvider): https://material-ui.com/styles/advanced/?
I read about MuiThemeProvider but could not find it in the material version 4 documentation. Is it obsolete? What's the difference between MuiThemeProvider and ThemeProvider?
React (client side rendering) & Material (latest versions)
Backend: Node
In Material-UI v5, you can use GlobalStyles to do exactly that. From what I know, GlobalStyles is just a wrapper of emotion's Global component. The usage is pretty straightforward:
import GlobalStyles from "#mui/material/GlobalStyles";
<GlobalStyles
styles={{
h1: { color: "red" },
h2: { color: "green" },
body: { backgroundColor: "lightpink" }
}}
/>
Note that you don't even have to put it inside ThemeProvider, GlobalStyles uses the defaultTheme if not provided any:
return (
<>
<GlobalStyles
styles={(theme) => ({
h1: { color: theme.palette.primary.main },
h2: { color: "green" },
body: { backgroundColor: "lightpink" }
})}
/>
<h1>This is a h1 element</h1>
<h2>This is a h2 element</h2>
</>
);
Live Demo
You can actually write global styles with material UI:
const useStyles = makeStyles((theme) => ({
'#global': {
'.MuiPickersSlideTransition-transitionContainer.MuiPickersCalendarHeader-transitionContainer': {
order: -1,
},
'.MuiTypography-root.MuiTypography-body1.MuiTypography-alignCenter': {
fontWeight: 'bold',
}
}
}));
Global Styles with Material UI & React
// 1. GlobalStyles.js
import { createStyles, makeStyles } from '#material-ui/core';
const useStyles = makeStyles(() =>
createStyles({
'#global': {
html: {
'-webkit-font-smoothing': 'antialiased',
'-moz-osx-font-smoothing': 'grayscale',
height: '100%',
width: '100%'
},
'*, *::before, *::after': {
boxSizing: 'inherit'
},
body: {
height: '100%',
width: '100%'
},
'#root': {
height: '100%',
width: '100%'
}
}
})
);
const GlobalStyles = () => {
useStyles();
return null;
};
export default GlobalStyles;
** Then Use it in App.js like below**
// 2. App.js
import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import { Router } from 'react-router-dom';
import { NavBar, Routes, GlobalStyles, Routes } from '../';
const theme = createMuiTheme({
palette: {
primary: {
main: 'blue'
}
}
});
const App = () => {
return (
<MuiThemeProvider theme={theme}>
<Router>
<NavBar />
<GlobalStyles />
<Routes />
</Router>
</MuiThemeProvider>
);
};
export default App;
This Works for me with my react project.
For global styles you can use it like shown below.
This is the best implementation that has worked for me.
const theme = createMuiTheme({
overrides: {
MuiCssBaseline: {
'#global': {
html: {
WebkitFontSmoothing: 'auto',
},
},
},
},
});
// ...
return (
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
);
For more reference: Global CSS
In my experience, using MuiThemeProvider and createMuiTheme have worked wonderfully. However, I am using Material-UI version 3.9.2.
MuiThemeProvider should wrap around your entire application. All you need to do in all of your components would be to instead of passing your styles object to with styles, pass a function that passes in the theme.
Ex:
import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '#material-ui/core/styles';
import {NavBar, Routes} from '../'
const theme = createMuiTheme({
palette: {
primary: {
main: 'red'
},
},
/* whatever else you want to add here */
});
class App extends Component {
render() {
return (
<MuiThemeProvider theme={theme}>
<NavBar />
<Routes />
</MuiThemeProvider>
)
}
then in navbar let's say:
import React from 'react';
import { withStyles } from '#material-ui/core';
const styles = theme => ({
root: {
color: theme.palette.primary.main,,
}
})
const NavBar = ({classes}) => {
return <div className={classes.root}>navigation</div>
}
export default withStyles(styles)(NavBar);
Hope that helps, works very well for me!

Add custom theme variable in createTheme()

By default the MUI theme is a combination of several pre-defined objects such as typography: {...}, palette: {...} etc.
Is is possible to add a custom object into this setup and still use createTheme?
So for example the theme object would become:
const theme = {
palette: {
primary: '#000'
},
typography: {
body1: {
fontFamily: 'Comic Sans'
}
},
custom: {
myOwnComponent: {
margin: '10px 10px'
}
}
}
Yes, this works just fine. Material-UI does a deep merge of its defaults with the object you provide with some special handling for keys that get merged in a more sophisticated fashion (such as palette, typography and a few others). Any unrecognized keys will come through unchanged.
Below is a working example:
import React from "react";
import ReactDOM from "react-dom";
import {
useTheme,
createMuiTheme,
MuiThemeProvider
} from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Typography from "#material-ui/core/Typography";
const theme = createMuiTheme({
palette: {
primary: {
main: "#00F"
}
},
typography: {
body1: {
fontFamily: "Comic Sans"
}
},
custom: {
myOwnComponent: {
margin: "10px 10px",
backgroundColor: "lightgreen"
}
}
});
const MyOwnComponent = () => {
const theme = useTheme();
return (
<div style={theme.custom.myOwnComponent}>
Here is my own component using a custom portion of the theme.
</div>
);
};
function App() {
return (
<MuiThemeProvider theme={theme}>
<div className="App">
<Button variant="contained" color="primary">
<Typography variant="body1">
Button using main theme color and font-family
</Typography>
</Button>
<MyOwnComponent />
</div>
</MuiThemeProvider>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
You can add custom variables in your MUI theme as easy as:
const theme = createTheme({
myField: {
myNestedField: 'myValue',
},
});
But if you're using Typescript, you also need to update the definition of ThemeOptions and Theme using module augmentation:
declare module '#mui/material/styles' {
// fix the type error when referencing the Theme object in your styled component
interface Theme {
myField?: {
myNestedField?: string;
};
}
// fix the type error when calling `createTheme()` with a custom theme option
interface ThemeOptions {
myField?: {
myNestedField?: string;
};
}
}
If you want to reuse the type between Theme and ThemeOptions, you can define a common interface and inherit it in both places:
declare module '#mui/material/styles' {
interface CustomTheme {
myField?: {
myNestedField?: string;
};
}
interface Theme extends CustomTheme {}
interface ThemeOptions extends CustomTheme {}
}
Also note that you don't have to create custom variables in MUI theme if you want to override a custom component using createTheme(). See this answer for more detail.
Live Demo
On top of the answers above, if you are using sx for styling you can access the custom theme like so:
<div sx={{ margin: (theme) => theme.custom.myOwnComponent.margin }} />

Customize Material UI ToolTip

I'm trying to customize material ui tooltip for react storybook
I have tried changing some css properties like width, height, background color but failed to see those changes
import * as React from 'react';
import { createStyles, withStyles, Tooltip, IconButton } from '#material-ui/core';
const styles = (theme: any) => createStyles({
tooptip: {
width: "92px",
height: "36px",
borderRadius: "18px",
boxShadow: "0 20px 80px 0",
backgroundColor:"red"
}
});
interface ToolTipProps {
children?: JSX.Element[] | JSX.Element;
classes?: { [key:string]: string };
}
function ToolTip({ classes }: ToolTipProps): JSX.Element {
return (
<Tooltip title="Tooltip" classes={classes}>
<div>Hover</div>
</Tooltip>
);
}
export default withStyles(styles)(ToolTip);
I need to customize tooltip
import React from "react";
import { withStyles } from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import Tooltip from "#material-ui/core/Tooltip";
const styles = {
tooltip: {
width: "92px",
height: "36px",
borderRadius: "18px",
boxShadow: "0 20px 80px 0",
backgroundColor: "red"
}
};
const CustomTooltip = withStyles(styles)(Tooltip);
function MyCustomTooltip() {
return (
<CustomTooltip title="Tooltip">
<Button>Custom Tooltip</Button>
</CustomTooltip>
);
}
export default MyCustomTooltip;
Live demo
You have to do Typescript stuff by yourself. I don't use it, so I don't know how it should be done :).
Another way to customize material-ui components would be to use themes.
import { createMuiTheme } from "#material-ui/core/styles";
import lightGreen from "#material-ui/core/colors/lightGreen";
import lime from "#material-ui/core/colors/lime";
import teal from "#material-ui/core/colors/teal";
import yellow from "#material-ui/core/colors/yellow";
import deepOrange from "#material-ui/core/colors/deepOrange";
export default createMuiTheme({
palette: {
primary: lime,
secondary: teal,
error: deepOrange,
action: {
disabledBackground: teal[400]
},
text: {
primary: lightGreen[900],
secondary: teal[700],
disabled: yellow[600]
}
},
status: {
danger: "orange"
}
});
and then wrap your app / component implementation in material-ui ThemeProvider
import GardenTheme from './themes';
/* your story / component code */
return (
<ThemeProvider theme={GardenTheme}>
/* tooltip */
</ThemeProvider>
);
I wrote a short article on usage of material-ui themes on medium link

Resources