I've written a React component, Button:
import PropTypes from 'prop-types'
import Radium from 'radium'
import React from 'react'
import { Icon } from 'components'
import { COLOURS, GLOBAL_STYLES, ICONS, MEASUREMENTS } from 'app-constants'
#Radium
export default class Button extends React.Component {
static propTypes = {
children: PropTypes.string,
dark: PropTypes.bool,
icon: PropTypes.oneOf(Object.values(ICONS)).isRequired,
style: PropTypes.object,
}
render() {
const { children, dark, icon, style } = this.props
let mergedStyles = Object.assign({}, styles.base, style)
if (!children)
mergedStyles.icon.left = 0
if (dark)
mergedStyles = Object.assign(mergedStyles, styles.dark)
return (
<button
className="btn btn-secondary"
style={mergedStyles}
tabIndex={-1}>
<Icon name={icon} style={mergedStyles.icon} />
{children &&
<span style={mergedStyles.text}>{children}</span>
}
</button>
)
}
}
export const styles = {
base: {
backgroundColor: COLOURS.WHITE,
border: `1px solid ${COLOURS.BORDER_LIGHT}`,
borderRadius: GLOBAL_STYLES.BORDER_RADIUS,
cursor: 'pointer',
padding: GLOBAL_STYLES.BUTTON_PADDING,
':focus': {
outline: 'none',
},
':hover': {
boxShadow: GLOBAL_STYLES.BOX_SHADOW,
},
icon: {
fontSize: GLOBAL_STYLES.ICON_SIZE_TINY,
left: '-3px',
verticalAlign: 'middle',
},
text: {
fontSize: GLOBAL_STYLES.FONT_SIZE_TINY,
fontWeight: GLOBAL_STYLES.FONT_2_WEIGHT_MEDIUM,
marginLeft: `${MEASUREMENTS.BUTTON_PADDING.HORIZONTAL}px`,
verticalAlign: 'middle',
},
},
dark: {
backgroundColor: COLOURS.PRIMARY_3,
border: `1px solid ${COLOURS.PRIMARY_2}`,
color: COLOURS.WHITE,
':hover': {
boxShadow: GLOBAL_STYLES.BOX_SHADOW_DARK,
},
},
}
I've also written a test for Button with Jest and Enzyme, which validates if its dark styles are applied when its dark prop is set to true:
import { ICONS } from 'app-constants'
import Button, { styles } from 'components/Button'
describe("<Button>", () => {
let props
let mountedComponent
const getComponent = () => {
if (!mountedComponent)
mountedComponent = shallow(
<Button {...props} />
)
return mountedComponent
}
beforeEach(() => {
mountedComponent = undefined
props = {
children: undefined,
dark: undefined,
icon: ICONS.VIBE,
style: undefined,
}
})
describe("when `dark` is `true`", () => {
beforeEach(() => {
props.dark = true
})
it("applies the component's `dark` styles", () => {
const componentStyles = getComponent().props().style
expect(componentStyles).toEqual(expect.objectContaining(styles.dark))
})
})
})
As you can see, I do this by checking if the properties of styles.dark are inside the rendered Button's style attribute. If they are, then it means the styles have applied successfully.
The issue is that styles.dark and componentStyles don't match:
Output of console.log(styles.dark)
ObjectContaining{
":hover": {
"boxShadow": "0px 0px 0px 2px rgba(0,0,0,0.2)"
},
"backgroundColor": [Object],
"border": "1px solid rgb(47, 52, 63)",
"color": [Object]
}
Output of console.log(componentStyles)
{
"backgroundColor": "rgb(31, 34, 40)",
"border": "1px solid rgb(47, 52, 63)",
"borderRadius": "4px",
"color": "rgb(255, 255, 255)",
"cursor": "pointer",
"padding": "3px 5px 3px 5px"
}
I notice a few issues here:
styles.dark has several Color() [Object]s from the color library. They haven't outputted their rgb() value as a string, but the same properties in componentStyles have, thus resulting in a mismatch.
componentStyles has Radium's interactive styles stripped, such as :focus and :hover (I assume Radium does this during rendering triggered by Enzyme's shallow() function). This causes a mismatch with styles.dark, which doesn't have these properties stripped.
As a result, I'm not sure how to test this. I can't think of any alternative solutions to validate that styles.dark has been applied. I think that doing the following to styles.dark during testing would be a solution:
Recursively cause all Color() [Object]s to process so they output their rgb() value as a string.
Recursively remove all interactive Radium styles (like :focus and :hover)
Doing so would cause styles.dark to equal the value of componentStyles, thus passing the test. I'm just not sure how to do it.
I came back to this a few days later with fresh eyes and thought of a solution:
describe("<Button>", () => {
let props
let mountedComponent
let defaultComponent
const getComponent = () => {
if (!mountedComponent)
mountedComponent = shallow(
<Button {...props} />
)
return mountedComponent
}
beforeEach(() => {
props = {
children: undefined,
dark: undefined,
icon: ICONS.VIBE,
style: undefined,
}
defaultComponent = getComponent()
mountedComponent = undefined
})
describe("when `dark` is `true`", () => {
beforeEach(() => {
props.dark = true
})
it("applies the component's `dark` styles", () => {
const darkStyles = getComponent().props().style
expect(defaultComponent.props().style).not.toEqual(darkStyles)
})
})
})
Rather than asserting that the rendered component's style prop contains the styles.dark (which is brittle), it just checks to see if the styles have changed at all when the dark prop is set to true.
Related
I am trying to create a SvgIcon component that I pass an SVG to through the props.
Because of the way React handles SVGs, when they're imported as ReactComponents (e.g. import { ReactComponent as ArrowIcon } from "icons/arrow.svg") I have to define my component in a dynamic way.
This is what I have so far:
const styleSvgIcon = ({ theme, stroke, fill, size, icon: Icon }) => styled(
Icon
).attrs({
viewBox: `0 0 24 24`,
})`
path {
${stroke && `stroke: ${calculateColor({ color: stroke, theme })};`}
${fill && `fill: ${calculateColor({ color: fill, theme })};`}
}
height: ${calculateSize(size)};
width: ${calculateSize(size)};
`;
const SvgIcon = ({ stroke, fill, size, icon }) => {
const theme = useTheme();
const StyledIcon = styleSvgIcon({ theme, stroke, fill, size, icon });
console.log('styledddddddddd', StyledIcon); // prints the styled component with the new styles, but on the page nothing changes
return <StyledIcon />;
};
SvgIcon.propTypes = {
stroke: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
fill: PropTypes.oneOf(Object.values(SVG_ICON_COLORS)),
size: PropTypes.oneOf(Object.values(SVG_ICON_SIZES)),
icon: PropTypes.elementType.isRequired,
};
export default SvgIcon;
Here's my story definition:
import React from 'react';
import SvgIcon from './SvgIcon';
import * as all_icons from '../icons';
import { SVG_ICON_SIZES, SVG_ICON_COLORS } from '../constants/variants';
export default {
title: 'media/SvgIcon',
component: SvgIcon,
argTypes: {
size: {
type: 'select',
options: Object.values(SVG_ICON_SIZES),
defaultValue: SVG_ICON_SIZES.SMALL,
},
stroke: {
type: 'select',
options: Object.values(SVG_ICON_COLORS),
defaultValue: SVG_ICON_COLORS.PRIMARY,
},
fill: {
type: 'select',
options: Object.values(SVG_ICON_COLORS),
defaultValue: SVG_ICON_COLORS.PRIMARY,
},
},
};
const Template = (args) => {
const icons = Object.values(all_icons);
// return icons.map((SvgComponent, i) => (
return icons
.slice(0, 2)
.map((SvgComponent, i) => (
<SvgIcon key={i} {...args} icon={SvgComponent} />
));
};
export const Small = Template.bind({});
Small.args = {
size: SVG_ICON_SIZES.SMALL,
};
export const Medium = Template.bind({});
Medium.args = {
size: SVG_ICON_SIZES.MEDIUM,
};
export const Large = Template.bind({});
Large.args = {
size: SVG_ICON_SIZES.LARGE,
};
export const XL = Template.bind({});
XL.args = {
size: SVG_ICON_SIZES.XL,
};
This works fine locally, but when I deploy my app and try to change the props through Storybook, nothing gets updated.
However, in production, the controls do nothing.
I FIGURED IT OUT!!!
So because I was just setting the styles without using the props like this:
size: ${calculate(size)};
styled-components somehow knows and therefore doesn't add listeners to updated props. So my StyledIcon just becomes a static component that does not update when new styles are passed in since they are just set in stone.
Instead, passing them as props and accessing them through props adds those listeners
const SvgIcon = ({ stroke, fill, size, icon: Icon }) => {
const StyledIcon = styled(Icon).attrs({
viewBox: `0 0 24 24`,
})`
path {
stroke: ${({ stroke, theme }) =>
calculateColor({ color: stroke, theme })};
fill: ${({ fill, theme }) => calculateColor({ color: fill, theme })};
}
height: ${({ size }) => calculateSize(size)};
width: ${({ size }) => calculateSize(size)};
`;
return (
<div>
<StyledIcon size={size} fill={fill} stroke={stroke} />,{size},{fill},
{stroke}
<StyledArrowUpIcon stroke={stroke} size={size} fill={fill} />
</div>
);
};
I have a Spinner component that's basically a loading icon. I'm trying to pass props to the JSS styles so that it can be customized. But the animations don't seem to work if I pass props to the keyframes.
Below is the component. When I use the animation $spinnertest it works fine. If I use $spinners, it doesn't load the animation (when inspecting the elements, animation-name doesn't even show up in the class, leading me to believe it doesn't get generated. ).
**Example CodeSandBox of issue (just change animation to spinners): https://codesandbox.io/s/exciting-shirley-pqt1o?fontsize=14&hidenavigation=1&theme=dark
const useStyles = makeStyles(theme => ({
root: props => ({
width: props.size,
height: props.size,
position: 'relative',
contain: 'paint',
display: 'inline-block',
}),
spinner: props => ({
width: props.size*0.3125,
height: props.size*0.3125,
background: props.color,
position: 'absolute',
animationDuration: props.duration,
animationIterationCount: 'infinite',
animationTimingFunction: 'ease-in-out',
}),
spinnerAnimation: {
animationName: '$spinners',
},
square2: props => ({
animationDelay: -props.duration/2,
}),
'#keyframes spinnertest': {
'25%': {
transform: 'translateX(22px) rotate(-90deg) scale(.5)',
},
'50%': {
transform: 'translateX(22px) translateY(22px) rotate(-180deg)',
},
'75%': {
transform: 'translateX(0) translateY(22px) rotate(-270deg) scale(.5)',
},
'to': {
transform: 'rotate(-1turn)',
},
},
'#keyframes spinners': props => ({
'25%': {
transform: `translateX(${props.translate}px) rotate(-90deg) scale(.5)`,
},
'50%': {
transform: `translateX(${props.translate}px) translateY(${props.translate}px) rotate(-180deg)`,
},
'75%': {
transform: `translateX(0) translateY(${props.translate}px) rotate(-270deg) scale(.5)`,
},
'to': {
transform: `rotate(-1turn)`,
},
}),
}));
export default function Spinner(props) {
const {duration, size, color} = props;
const classes = useStyles({
duration: duration,
size: size,
color: color,
translate: size*(1-0.3125),
});
return (
<Box className={classes.root}>
<Box className={clsx(classes.spinner, classes.spinnerAnimation)} />
<Box className={clsx(classes.spinner, classes.square2, classes.spinnerAnimation)} />
</Box>
)
}
Spinner.defaultProps = {
duration: 1800,
size: 32,
color: #fff,
}
I have a turnaround solution, which works (not that pretty). You would turn your withStyles into a currying function, that takes keyframesProps, and at your key frame definition you would use an IIFE that returns the object with its properties:
const useStyles = keyframesProps => makeStyles((theme) => ({
... all other styles,
// you need to call an IIFE because keyframes doesn't receive a function
"#keyframes spinners": ((props) => ({
"25%": {
transform: `translateX(${props.translate}px) rotate(-90deg) scale(.5)`
},
"50%": {
transform: `translateX(${props.translate}px) translateY(${props.translate}px) rotate(-180deg)`
},
"75%": {
transform: `translateX(0) translateY(${props.translate}px) rotate(-270deg) scale(.5)`
},
to: {
transform: `rotate(-1turn)`
}
}))(keyframesProps)
}));
at your component you would define your classes like:
const styleProps = {
duration: duration,
size: size,
color: color
}
const framesProps = {
translate: size * (1 - 0.3125)
}
const classes = useStyles(framesProps)(styleProps);
It sounds that MUI has a bug around props in makeStyles #keyframes
#16673
as Olivier Tassinari stated, this bug will be fixed in v5 where MUI gonna use a new styling solution styled-components RCF #22342.
The problem is even more general:
The arrow functions (with or without props) do not work within makeStyles
#21011
Passing the props to rules in your defined keyframes will fix it (after v5 has been available, hopefully)
"#keyframes spinners": {
"25%": {
transform: (props) =>
// console.log(props) and template generation will be created correctly.
`translateX(${props.translate}px) rotate(-90deg) scale(.5)`
},
// ...
}
Until then you can use higher-order useStyle creator for embedding your keyframes, as #buzatto suggested.
Or define your animation presets in your theme object and uses them globally around your project.
const theme = createMuiTheme({
animation: {
presets: {
duration: 180,
// or even function
rotateDeg: (angle) => `{angle}deg`
//...
}
}
});
// usage
const useStyles = makeStyles(theme => ({
"#keyframes spinners": {
"25%": {
transform: `translateX(${
theme.animation.presets.duration * 10
}px) rotate(${theme.animation.presets.rotateDeg(-90)}) scale(.5)`,
},
},
}
I want to snapshot a component in React using react-test-renderer. The component I want to test receives a ref from another component. The component I'm testing relies on a function implemented by the component which is passing the ref as props:
import React from "react";
import { makeStyles, Paper, Typography } from "#material-ui/core";
import { INodeInfoProps } from "./interfaces";
const useStyles = makeStyles({
container: {
position: "absolute",
padding: 10,
maxHeight: 600,
width: 400,
overflowWrap: "break-word",
"& p": {
fontSize: 12,
},
},
channels: {
display: "flex",
},
channelsComponent: {
marginLeft: 5,
},
});
export const NodeInfo: React.FC<INodeInfoProps> = ({ graphRef, info }) => {
const classes = useStyles();
const getDivCoords = () => {
if (graphRef.current) {
const nodeCoordinates = graphRef.current.graph2ScreenCoords(
info?.x || 0,
info?.y || 0,
info?.z || 0
);
return {
top: nodeCoordinates.y + 20,
left: nodeCoordinates.x,
};
}
return { top: 0, left: 0 };
};
if (info && graphRef.current) {
return (
<Paper
className={classes.container}
style={{
top: getDivCoords().top,
left: getDivCoords().left,
}}
>
<Typography>Pubkey: {info.publicKey}</Typography>
<Typography>Alias: {info.alias}</Typography>
</Paper>
);
}
return null;
};
So the function graph2ScreenCoords is implemented in the component which the ref is received by props by my component.
My test component would look like this:
import React from "react";
import renderer from "react-test-renderer"
import {NodeInfo} from "../index";
it('should render each node info', () => {
const info = {
publicKey: "test123",
alias: "test",
color: "#fff",
visible: true,
links: [
{
channelId: "123",
node1: "test123",
node2: "test345",
capacity: "10000",
color: "#fff"
}
]
}
const tree = renderer.create(<NodeInfo graphRef={} info={info}/>).toJSON()
expect(tree).toMatchSnapshot();
})
But I need to pass the ref to the test component, so it can access the function graph2ScreenCoords.
How should I make it the right way? Should I render the component in my test, create a ref and pass it as props? Should I mock the ref? How?
Thanks in advance
I have event handlers for things like onClick or onFocus, and I can't figure out how to use the theme inside of the handler code. I want to change the color of an iconButton and I don't want to hard-code the color because we want components that can be general use, and eventually work with themes using completely different colors.
Tried using withTheme in addition to withStyles, so I can get the theme inside of the render(), but I can't get to it from a handler called from that rendering. Tried passing it, calling as a prop, declaring constants based upon theme values in the class (both inside and outside of render), nothing.
I don't know if this is possible, or not built in, or what. I'm hoping that I'm just missing something.
Environment: CodeSandBox, so CreateReactApp. Material-UI plus React-Select, withStyles and withTheme (useTheme help here?).
handleInfoClick = (e) => {
if (this.instructionsContent.current.style.display !== "block") {
this.instructionsContent.current.style.display = "block";
this.instructionsButton.current.style.color = "#f9be00"; //works
} else {
this.instructionsContent.current.style.display = "none";
this.instructionsButton.current.style.color = this.theme.palette.text.disabled; // doesn't work
also tried this:
handleSelectFocus = () => {
if (this.state.visited === false) {
this.instructionsContent.current.style.display = "block";
this.instructionsButton.current.style.color = this.activeButtonColor;
this.setState({ visited: true });
}
};
...
render() {
const { theme } = this.props;
...
const activeButtonColor = theme.palette.secondary.main;
Finally, also tried to use the classes I can use within render(), but it doesn't recognize those either:
const styles = theme => ({
...
infoButton: {
position: "absolute",
bottom: 0,
left: 0,
marginBottom: 20,
width: 48,
color: theme.palette.text.disabled,
"&:active": {
color: theme.palette.secondary.main
}
},
infoButtonActive: {
position: "absolute",
bottom: 0,
left: 0,
marginBottom: 20,
width: 48,
color: theme.palette.secondary.main
},
....
Hoping one of these approaches would give me a color for my <IconButton> - from my theme:
<div className={classes.infoButtonDiv}>
<IconButton
aria-label="Instructions"
className={classes.infoButton}
buttonRef={this.instructionsButton}
onClick={this.handleInfoClick}
>
<HelpOutline />
</IconButton>
</div>
(in a different theme.js file applied to the root element:
const theme = createMuiTheme({
typography: {
fontFamily: ["Roboto", '"Helvetica Neue"', "Arial", "sans-serif"].join(",")
},
palette: {
primary: {
main: "#00665e"
},
secondary: {
main: "#f9be00"
}
},
overrides: {
LeftNav: {
drawerDiv: {
backgroundColor: "#00665e",
width: 300
}
}
},
direction: "ltr",
typography: {
useNextVariants: true
}
});
Triggering a state change onClick will update the color, but only if you pass one of the supported values for the IconButton color prop ("primary" or "secondary").
import React, { Component } from "react";
import IconButton from "#material-ui/core/IconButton";
import DeleteIcon from "#material-ui/icons/Delete";
class ButtonStyle extends Component {
constructor(props) {
super(props);
this.state = {
buttonColor: "primary"
};
}
handleClick = e => {
this.setState({
buttonColor: "secondary"
});
};
render() {
const buttonColor = this.state.buttonColor;
return (
<div>
<IconButton
aria-label="Delete"
color={buttonColor}
onClick={this.handleClick}
>
<DeleteIcon />
</IconButton>
</div>
);
}
}
export default ButtonStyle;
Given the Card code as in here. How can I update the card style or any material UI style as from:
const styles = theme => ({
card: {
minWidth: 275,
},
To such follows:
const styles = theme => ({
card: {
minWidth: 275, backgroundColor: props.color
},
when I tried the latest one, I got
Line 15: 'props' is not defined no-undef
when I updated code to be :
const styles = theme => (props) => ({
card: {
minWidth: 275, backgroundColor: props.color
},
also
const styles = (theme ,props) => ({
card: {
minWidth: 275, backgroundColor: props.color
},
Instead of
const styles = theme => ({
card: {
minWidth: 275, backgroundColor: props.color
},
I got the component card style at the web page messy.
By the way, I pass props as follows:
<SimpleCard backgroundColor="#f5f2ff" />
please help!
Deleted the old answer, because it's no reason for existence.
Here's what you want:
import React from 'react';
import { makeStyles } from '#material-ui/core';
const useStyles = makeStyles({
firstStyle: {
backgroundColor: props => props.backgroundColor,
},
secondStyle: {
color: props => props.color,
},
});
const MyComponent = ({children, ...props}) =>{
const { firstStyle, secondStyle } = useStyles(props);
return(
<div className={`${firstStyle} ${secondStyle}`}>
{children}
</div>
)
}
export default MyComponent;
Now you can use it like:
<MyComponent color="yellow" backgroundColor="purple">
Well done
</MyComponent>
Official Documentation
Solution for how to use both props and theme in material ui :
const useStyles = props => makeStyles( theme => ({
div: {
width: theme.spacing(props.units || 0)
}
}));
export default function ComponentExample({ children, ...props }){
const { div } = useStyles(props)();
return (
<div className={div}>{children}</div>
);
}
Here the Typescript solution:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import Button from '#material-ui/core/Button';
import {Theme} from '#material-ui/core';
export interface StyleProps {
height: number;
}
const useStyles = makeStyles<Theme, StyleProps>(theme => ({
root: {
background: 'green',
height: ({height}) => height,
},
}));
export default function Hook() {
const props = {
height: 48
}
const classes = useStyles(props);
return <Button className={classes.root}>Styled with Hook API</Button>;
}
If you want to play with it, try it in this CodeSandbox
In MUI v5, this is how you access the props when creating the style object using styled():
import { styled } from "#mui/material";
const StyledBox = styled(Box)(({ theme, myColor }) => ({
backgroundColor: myColor,
width: 30,
height: 30
}));
For folks who use typescript, you also need to add the prop type to the CreateStyledComponent:
type DivProps = {
myColor: string;
};
const Div = styled(Box)<DivProps>(({ theme, myColor }) => ({
backgroundColor: myColor,
width: 30,
height: 30
}));
<StyledBox myColor="pink" />
If you want to use system props in your custom component like Box and Typography, you can use extendSxProp like the example below:
import { unstable_extendSxProp as extendSxProp } from "#mui/system";
const StyledDiv = styled("div")({});
function DivWithSystemProps(inProps) {
const { sx } = extendSxProp(inProps);
return <StyledDiv sx={sx} />;
}
<DivWithSystemProps
bgcolor="green"
width={30}
height={30}
border="solid 1px red"
/>
Explanation
styled("div")(): Add the sx props to your custom component
extendSxProp(props): Gather the top level system props and put it inside the sx property:
const props = { notSystemProps: true, color: 'green', bgcolor: 'red' };
const finalProps = extendSxProp(props);
// finalProps = {
// notSystemProps: true,
// sx: { color: 'green', bgcolor: 'red' }
// }
To use with typescript, you need to add the type for all system properties:
type DivSystemProps = SystemProps<Theme> & {
sx?: SxProps<Theme>;
};
function DivWithSystemProps(inProps: DivSystemProps) {
const { sx, ...other } = extendSxProp(inProps);
return <StyledDiv sx={sx} {...other} />;
}
Here's the official Material-UI demo.
And here's a very simple example. It uses syntax similar to Styled Components:
import React from "react";
import { makeStyles, Button } from "#material-ui/core";
const useStyles = makeStyles({
root: {
background: props => props.color,
"&:hover": {
background: props => props.hover
}
},
label: { fontFamily: props => props.font }
});
export function MyButton(props) {
const classes = useStyles(props);
return <Button className={classes.root} classes={{ label: classes.label }}>My Button</Button>;
}
// and the JSX...
<MyButton color="red" hover="blue" font="Comic Sans MS" />
This demo uses makeStyles, but this feature is also available in styled and withStyles.
This was first introduced in #material-ui/styles on Nov 3, 2018 and was included in #material-ui/core starting with version 4.
This answer was written prior to version 4.0 severely out of date!
Seriously, if you're styling a function component, use makeStyles.
The answer from James Tan is the best answer for version 4.x
Anything below here is ancient:
When you're using withStyles, you have access to the theme, but not props.
Please note that there is an open issue on Github requesting this feature and some of the comments may point you to an alternative solution that may interest you.
One way to change the background color of a card using props would be to set this property using inline styles. I've forked your original codesandbox with a few changes, you can view the modified version to see this in action.
Here's what I did:
Render the component with a backgroundColor prop:
// in index.js
if (rootElement) {
render(<Demo backgroundColor="#f00" />, rootElement);
}
Use this prop to apply an inline style to the card:
function SimpleCard(props) {
// in demo.js
const { classes, backgroundColor } = props;
const bull = <span className={classes.bullet}>•</span>;
return (
<div>
<Card className={classes.card} style={{ backgroundColor }}>
<CardContent>
// etc
Now the rendered Card component has a red (#F00) background
Take a look at the Overrides section of the documentation for other options.
#mui v5
You can use styled() utility (Make sure that you're importing the correct one) and shouldForwardProp option.
In the following example SomeProps passed to a div component
import { styled } from '#mui/material'
interface SomeProps {
backgroundColor: 'red'|'blue',
width: number
}
const CustomDiv = styled('div', { shouldForwardProp: (prop) => prop !== 'someProps' })<{
someProps: SomeProps;
}>(({ theme, someProps }) => {
return ({
backgroundColor: someProps.backgroundColor,
width: `${someProps.width}em`,
margin:theme.spacing(1)
})
})
import React from "react";
import { makeStyles } from "#material-ui/styles";
import Button from "#material-ui/core/Button";
const useStyles = makeStyles({
root: {
background: props => props.color,
"&:hover": {
background: props => props.hover
}
}
});
export function MyButton(props) {
const classes = useStyles({color: 'red', hover: 'green'});
return <Button className={classes.root}>My Button</Button>;
}
Was missing from this thread a props use within withStyles (and lead to think it wasn't supported)
But this worked for me (say for styling a MenuItem):
const StyledMenuItem = withStyles((theme) => ({
root: {
'&:focus': {
backgroundColor: props => props.focusBackground,
'& .MuiListItemIcon-root, & .MuiListItemText-primary': {
color: props => props.focusColor,
},
},
},
}))(MenuItem);
And then use it as so:
<StyledMenuItem focusColor={'red'} focusBackground={'green'}... >...</StyledMenuItem>
I spent a couple of hours trying to get withStyles to work with passing properties in Typescript. None of the solutions I found online worked with what I was trying to do, so I ended up knitting my own solution together, with snippets from here and there.
This should work if you have external components from, lets say Material UI, that you want to give a default style, but you also want to reuse it by passing different styling options to the component:
import * as React from 'react';
import { Theme, createStyles, makeStyles } from '#material-ui/core/styles';
import { TableCell, TableCellProps } from '#material-ui/core';
type Props = {
backgroundColor?: string
}
const useStyles = makeStyles<Theme, Props>(theme =>
createStyles({
head: {
backgroundColor: ({ backgroundColor }) => backgroundColor || theme.palette.common.black,
color: theme.palette.common.white,
fontSize: 13
},
body: {
fontSize: 12,
},
})
);
export function StyledTableCell(props: Props & Omit<TableCellProps, keyof Props>) {
const classes = useStyles(props);
return <TableCell classes={classes} {...props} />;
}
It may not be the perfect solution, but it seems to work. It's a real bugger that they haven't just amended withStyles to accept properties. It would make things a lot easier.
Solution for TypeScript with Class Component:
type PropsBeforeStyle = {
propA: string;
propB: number;
}
const styles = (theme: Theme) => createStyles({
root: {
color: (props: PropsBeforeStyle) => {}
}
});
type Props = PropsBeforeStyle & WithStyles<typeof styles>;
class MyClassComponent extends Component<Props> {...}
export default withStyles(styles)(MyClassComponent);
export const renderButton = (tag, method, color) => {
const OkButton = withStyles({
root: {
"color": `${color}`,
"filter": "opacity(0.5)",
"textShadow": "0 0 3px #24fda39a",
"backgroundColor": "none",
"borderRadius": "2px solid #24fda3c9",
"outline": "none",
"border": "2px solid #24fda3c9",
"&:hover": {
color: "#24fda3c9",
border: "2px solid #24fda3c9",
filter: "opacity(1)",
},
"&:active": {
outline: "none",
},
"&:focus": {
outline: "none",
},
},
})(Button);
return (
<OkButton tag={tag} color={color} fullWidth onClick={method}>
{tag}
</OkButton>
);
};
renderButton('Submit', toggleAlert, 'red')
Here's another way of dynamically passing props to hook's API in MUI v5
import React from "react";
import { makeStyles } from "#mui/styles";
import { Theme } from "#mui/material";
interface StyleProps {
height: number;
backgroundColor: string;
}
const useStyles = makeStyles<Theme>((theme) => ({
root: ({ height, backgroundColor }: StyleProps) => ({
background: backgroundColor,
height: height
})
}));
export default function Hook() {
const props = {
height: 58,
backgroundColor: "red"
};
const classes = useStyles(props);
return (
<button className={classes.root}>
another way of passing props to useStyle hooks
</button>
);
}
here's the codesandbox https://codesandbox.io/s/styles-with-props-forked-gx3bf?file=/demo.tsx:0-607
Here's 2 full working examples of how to pass props to MUI v5 styles. Either using css or javascript object syntax.
With css syntax:
import { styled } from '#mui/system'
interface Props {
myColor: string
}
const MyComponent = ({ myColor }: Props) => {
const MyStyledComponent = styled('div')`
background-color: ${myColor};
.my-paragraph {
color: white;
}
`
return (
<MyStyledComponent >
<p className="my-paragraph">Hello there</p>
</MyStyledComponent >
)
}
export default MyComponent
Note that we define MyStyledComponent within MyComponent, making the scoped props available to use in the template string of the styled() function.
Same thing with javascript object syntax:
import { styled } from '#mui/system'
const MyComponent = ({ className }: any) => {
return (
<div className={className}>
<p className="my-paragraph">Hello there</p>
</div>
)
}
interface Props {
myColor: string
}
const MyStyledComponent = styled(MyComponent)((props: Props) => ({
backgroundColor: props.myColor,
'.my-paragraph': { color: 'white' },
}))
export default MyStyledComponent
For this second example, please note how we pass the className to the component we want to apply the styles to. The styled() function will pass a className prop with the styles you define. You typically want to apply that to your root element. In this case the div.
Result:
I'm sure there's other variations of how to do this, but these two are easy to implement and understand.
You might need to memoize the calculated styles, and maybe not use this approach if your props changes a lot. I don't think it's very performant.
Using styled-components, sometimes you only want to apply styles if the prop is passed, in such cases you can do something like this (remove : {foo: boolean} if not using TypeScript):
const SAnchor = styled("a", {
shouldForwardProp: prop => prop !== "foo",
})(({foo = false}: {foo: boolean}) => ({
...(foo && {
color: "inherit",
textDecoration: "none",
}),
}));
Object spread source
shouldForwardProp docs
#mui v5
I use theme and prop from JSON object
const Answerdiv = styled((props) => {
const { item_style, ...other } = props;
return <div {...other}></div>;
})(({ theme, item_style }) => {
for(var i of Object.keys(item_style)){
item_style[i] =Object.byString(theme,item_style[i])|| item_style[i];
}
return (item_style)
});
component use
<Answerdiv item_style={(item_style ? JSON.parse(item_style) : {})}>
for Object.byString
Object.byString = function(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}