The purpose of this question is to understand what is happening under the hood. Every time I found the code with makeStyles()
I feel that I am just doing a pure
makeStyles(styles, [options]) => hook Link a style sheet with a function component using the hook pattern.
Arguments
styles (Function | Object): A function generating the styles or a styles object. It will be linked to the component. Use the function signature if you need to have access to the theme. It's provided as the first argument.
options (Object [optional]): options.defaultTheme (Object [optional]):
1.The default theme to use if a theme isn't supplied through a Theme Provider.
The other keys are forwarded to the options argument of jss.createStyleSheet([styles], [options]).. Returns hook: A hook. This hook can be used in a function component. The documentation often calls this returned hook useStyles. It accepts one argument: the properties that will be used for "interpolation" in the style sheet.
Examples
import React from 'react';
import { makeStyles } from '@material-ui/styles';
const useStyles = makeStyles({
root: {
backgroundColor: 'red',
color: props => props.color,
},
});
export default function MyComponent(props) {
const classes = useStyles(props);
return <div className={classes.root} />;
}
makeStyles
useStyles
) that will be used from within a function component.stylesOrCreator
. This is then normalized by the getStylesCreator function to be an object with a create
property that points at a function which will return a styles object.useStyles
function
makeStyles
is typically called useStyles
and is a custom hook. This means that it can only be called from within a function component and must be called unconditionally.useStyles
function, very little has happened. The function knows about its stylesCreator, but hasn't used it yet. Via the stylesCreator's options, the useStyles
function knows an index
that will later be used to determine the location in the <head>
of the style sheet for these styles relative to the other style sheets generated by other calls to makeStyles
/useStyles
.<head>
of style sheets generated by makeStyles/useStyles
.useStyles
makeStyles
. It should be called from within a function component to get a classes
object described below.props
object
props
of the function component this is used in. This will then be passed as an argument to any style rules where the value is a function.classes
object
classes.rulename
in your component rendering to apply that CSS class to an element.<head>
containing a CSS class per style rule.The bulk of the magic happens when you call the useStyles
function. The beginning of the function is here. Here are the key steps it performs:
classes
object.<head>
.