Passing props to material UI style
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>
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