How to use the concept of conditional classes in className when using mui v5 and styled components - material-ui

I'm aware that mui v5 is now using styled components but wanted to understand how to use the concept of conditional classes className={clsx(isRed && classes.bar)} when using styled components? How would the following example be best written with styled components?
mui v4 example using makeStyles:
import React from "react";
import clsx from "clsx";
import { makeStyles } from "#material-ui/core";
const useStyle = makeStyles({
bar: {
color: "red"
}
});
export const Foo: React.FC<{ isRed?: boolean }> = ({ isRed }) => {
const classes = useStyle();
return <div className={clsx(isRed && classes.bar)}>Hello World</div>;
};

You create a styled component:
import { styled } from "#mui/system";
// this will generate classNames and will assign to the div
const MainContainer = styled("div")({
position: "absolute",
borderRadius: "*px",
....
});
create conditional style objects:
const fullScreen = {
width: "100%",
height: "100vh",
};
const minScreen = {
width: "30%",
height: "40vh",
};
returned jsx
return (
<MainContainer
style={ifConditionTrue ? minScreen : fullScreen}
>
{children}
</MainContainer>
);

I am not sure if you asked for this but you can do these kind of things with conditions.
const useStyle = makeStyles({
departmentAddButton: {
position: "absolute",
maxHeight: 40,
minHeight: 0,
height: 33,
width: 100,
backgroundColor: "#404040", },
departmentAddButtonNoAbsolute: {
maxHeight: 40,
minHeight: 0,
height: 55,
width: 155,
backgroundColor: "#fff",
},
});
const foo = false;
className={clsx({
[classes.userAddButton]: foo === true,
[classes.departmentAddButton]: foo === false,
})}

Related

Material-UI Table/XGrid - How to set a different color for each cell

The styling for cell tables in material-ui is fine when you have a limited known amount of options but I'm struggling when is not known in advance.
To simplify, the idea is setting the background color for each cell based on the table cell values (let's imagine the value of the cell is actually the color).
Using cellRenderers is limited (not really a clean option).
The current solution looks like (doc):
cellClassName: (params: GridCellClassParams) =>
clsx('super-app', {
negative: (params.value as number) < 0,
positive: (params.value as number) > 0,
}),
How could create dynamically add styling or css in material-ui v5/emotion (doc). Something like :
cellSx: (params: GridCellClassParams) =>{
{
backgroundColor: params.value
}
}),
As per your question, I understood that you will receive color names and need to apply those colors on the cells in which the color names are present.
To dynamically create the object present in "clsx" method.
// let us consider that there is a key named color in the params which is received in the colums.
const generateColorsObject = (color) => {
const colorKey = color;
const colorObject = {}
colorObj[colorKey] = color
return colorObj; // it's value will have something like { 'red': 'red' }
}
const columns = [
{
field: 'name',
cellClassName: 'super-app-theme--cell',
},
{
field: 'score',
type: 'number',
width: 140,
cellClassName: (params) =>
clsx('super-app', generateColorsObject(params.color)),
},
];
const useStyles = makeStyles({
root: {
'& .super-app.red': {
backgroundColor: 'red', // you need to configure the background colors to the colorKey
color: '#1a3e72',
fontWeight: '600',
},
'& .super-app.blue': {
backgroundColor: 'blue',
color: '#1a3e72',
fontWeight: '600',
},
'& .super-app.orange': {
backgroundColor: 'orange',
color: '#1a3e72',
fontWeight: '600',
},
},
});
I think it boils down to the problem to create a mui class which applies the styling from the received props.
You can leverage material ui useStyles hook advanced feature to create mui classes which accepts the props, so you can pass over some style details as you want.
const useStyles = makeStyles({
// style rule
foo: props => ({
backgroundColor: props.backgroundColor,
}),
bar: {
// CSS property
color: props => props.color,
},
});
function MyComponent() {
// Simulated props for the purpose of the example
const props = { backgroundColor: 'black', color: 'white' };
// Pass the props as the first argument of useStyles()
const classes = useStyles(props);
return <div className={`${classes.foo} ${classes.bar}`} />
}
You can find the doc from here.
To solve this issue I used the cellClassName and changing the class using a function. Here is my working code:
// Based on the value of the cell the class will be applied.
const applyCellColour = (value: boolean) => (value ? 'notApprovedCell' : 'approvedCell');
// In the columns array in the cellClassName:
const columns: GridColDef[] = [
{
field: 'Approval',
headerName: 'Approval',
headerAlign: 'center',
align: 'center',
cellClassName: params => applyCellColour(params),
},
]
// CSS
.approvedCell {
background-color: 'green';
}
.notApprovedCell {
background-color: 'red';
}

How to set DialogTitle to Typography Variant h5?

I currently have lots of dialogs and want to change DialogTitle to have Typography h5 heading. Currently this works:
<DialogTitle>
<Typography variant="h5">Create Exercise</Typography>
</DialogTitle>
But I want this to be applied to all dialogs without having to add use the typography component. I also have tried the following with createTheme, but this does not change the fontSize.
const theme = createTheme({
components: {
MuiDialogTitle: {
styleOverrides: {
root: {
// Set this to h5
fontSize: "1.5rem",
},
},
},
},
});
Modify the DialogTitle component as mention below 👇
import MuiDialogTitle from "#material-ui/core/DialogTitle";
import Typography from "#material-ui/core/Typography";
import { withStyles } from "#material-ui/core/styles";
const styles = (theme) => ({
root: {
margin: 0,
padding: theme.spacing(2),
},
});
const DialogTitle = withStyles(styles)((props) => {
const { children, classes, ...other } = props;
return (
<MuiDialogTitle disableTypography className={classes.root} {...other}>
<Typography variant="h5">{children}</Typography>
</MuiDialogTitle>
);
});
export default DialogTitle;
use this component as DialogTitle, even you can modify the style and also able to add extra component into DialogTitle, like closing icon or some secondary title.

Correct way to style a section of a material-ui document

I have a header and want to style all of it's buttons differently than my global theme. I have tried using a child theme like:
<ThemeProvider
theme={(outerTheme) =>
_.merge(outerTheme, {
overrides: {
MuiButton: {
label: {
color: "#fff",
},
},
},
})
}
>
However, while I had expected this to override only MuiButton's in the child theme, it overrode them in them globally.
I know I can use makeStyles but, then, as far as I know, I have to reference it in all the child components which want to use the style. I'd like to wrap a higher level component and have all child components pick up the style. How is this done?
You can do this:
import Button from '#material-ui/core/Button';
import { purple } from '#material-ui/core/colors';
import { makeStyles } from '#material-ui/core/styles';
const useStyles = makeStyles((theme) => ({
header: {
"& button": {
marginRight: theme.spacing(1),
color: theme.palette.getContrastText(purple[500]),
backgroundColor: purple[500],
"&:hover": {
backgroundColor: purple[700],
},
},
},
});
function CustomHeader(props) {
const classes = useStyles();
return (
<div className={classes.header}>
<Button>Button 1</Button>
<Button>Button 2</Button>
<Button disabled>Button 3</Button>
</div>
)
};

Change onHover colour of TextField Material-UI v1

I m unable to change the onHover color of the TextField by overriding the classname. How can I do that?
I'm using material UI v1: https://github.com/callemall/material-ui/tree/v1-beta
Overriding with classes didn't help.
It worked by overriding MUIclass in createMuiTheme as below.
const theme = createMuiTheme({
overrides: {
MuiInput: {
underline: {
'&:hover:not($disabled):before': {
backgroundColor: 'rgba(0, 188, 212, 0.7)',
},
},
},
},
});
TextField is implemented using the Input component, which exposes a class named underline as part of its CSS API. Here is the the current definition of this class from the Input source:
underline: {
paddingBottom: 2,
'&:before': {
backgroundColor: theme.palette.input.bottomLine,
left: 0,
bottom: 0,
// Doing the other way around crash on IE11 "''" https://github.com/cssinjs/jss/issues/242
content: '""',
height: 1,
position: 'absolute',
right: 0,
transition: theme.transitions.create('backgroundColor', {
duration: theme.transitions.duration.shorter,
easing: theme.transitions.easing.ease,
}),
},
'&:hover:not($disabled):before': {
backgroundColor: theme.palette.text.primary,
height: 2,
},
'&$disabled:before': {
background: 'transparent',
backgroundImage: `linear-gradient(to right, ${theme.palette.input
.bottomLine} 33%, transparent 0%)`,
backgroundPosition: 'left top',
backgroundRepeat: 'repeat-x',
backgroundSize: '5px 1px',
},
},
To override the Input's classes, you need to pass them through the TextField using its InputProps property. Here is an example where I'm changing the color of the underline to green:
// define a class that will be used to modify the underline class
const styleSheet = createStyleSheet(theme => ({
greenUnderline: {
'&:before': {
backgroundColor: '#0f0',
},
},
}));
Override the Input's underline class via the TextField's InputProps:
<TextField
id="uncontrolled"
label="Uncontrolled"
defaultValue="foo"
className={classes.textField}
margin="normal"
InputProps={{ classes: { underline: classes.greenUnderline } }}
/>
This may not be exactly what you're looking to do, but it should get you started.
this worked for me:
export const theme = createMuiTheme({
overrides:{
MuiFilledInput:{
root:{
"&:hover": {
backgroundColor: '#5dc2a6',
}
}
}
});

How to add "Follow the link popup" into TinyMCE 4

I implemented somethink like on this picture:
if you click on a link popup will appear and you can follow the link.
jQuery(function($){
/**
* add the follow link popup to all TinyMCE instances
*/
if (!window.tinymce) return;
tinymce.on('AddEditor', function( event ) {
tinymce.editors.forEach(function(editor) {
if (!editor.isFollowLinkAdded) {
editor.isFollowLinkAdded = true;
editor.on('blur', function(e) {
jQuery(e.target.contentDocument.body).find('#followLink').remove();
});
editor.on('click', function(e) {
var link = jQuery(e.target).closest('a');
jQuery(e.view.document.body).find('#followLink').remove();
if (link.length) {
e.preventDefault();
var POPUP_WIDTH = 215,
isRightSide = (jQuery(e.view.document).width()-e.pageX) >= POPUP_WIDTH,
boxCss = {
top: e.pageY,
padding: '6px 10px',
position: 'absolute',
backgroundColor: '#ffffff',
border: '1px solid #a8a8a8',
borderRadius: '2px',
boxShadow: '0 1px 3px rgba(0, 0, 0, 0.2)',
color: '#666666',
cursor: 'pointer',
whiteSpace: 'nowrap',
zIndex: 502
};
boxCss[(isRightSide) ? 'left' : 'right'] = (isRightSide) ? e.pageX : jQuery(e.view.document).width()-e.pageX;
jQuery('<a/>', {
href: link.attr('href'),
text: link.attr('href'),
target: '_blank'
}).css({
cursor: 'pointer',
display: 'inline-block',
maxWidth: '100px',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap'
}).wrap(
jQuery('<p/>', {
text: 'Click to follow: ',
id: 'followLink',
}).on('click', function(){
var win = window.open(link.attr('href'), '_blank');
win.focus();
}).css(boxCss)
).parent().appendTo(e.view.document.body);
}
});
}
});
}, true );
});
The most recent version of TinyMCE 4 (4.5.3) includes the option to open a link in the right click menu of the editor - no need to write your own custom code.