Reputation: 255
I have severals .js files that using { makeStyles } from "@material-ui/core/styles";
to generate jss. Im using className={classes.myClass}
and in the end I'm calling it with const classes = useStyles();
This is a pretty well known setup. The problem is that I'm using same the jss code in all of my react Components. Its pretty repeatable and time consuming because the jss code need to be changed in every file when developing.
I've tried to make a separate file with all jss code and then export and import it, but then I get the problem that className={classes.myClass}
returning classes
don't exist or not declared, which is true because const classes = useStyles()
are now in another file.
Code example:
component1.js
{....}
const useStyles = makeStyles ({
myfontStyle: {
color: "red"
},
});
export default function Component1() {
const classes = useStyles();
return (
<div className={classes.myfontStyle}>
Helo world
</div>
)
};
component2.js
{....}
const useStyles = makeStyles ({
myfontStyle: {
color: "red"
},
});
export default function Component2() {
const classes = useStyles();
return (
<div className={classes.myfontStyle}>
Helo world
</div>
)
};
As we see, those 2 components share the same jss but still I need to repeat it twice.
So how do i proper make a solution for this? Thanks for all answers.
Upvotes: 3
Views: 678
Reputation: 203373
At a minimum you'll need the classes = useStyles()
in each component you want to use the useStyles
react hook in. There is nothing stopping you from defining your custom hook in it's own file and importing it into the components you want to use the styles in.
export const useMyFontStyles = makeStyles ({
myfontStyle: {
color: "red"
},
});
In the components:
import { useMyFontStyles } from '../path/to/useMyFontStyles';
export default function Component2() {
const classes = useMyFontStyles();
return (
<div className={classes.myfontStyle}>
Helo world
</div>
)
};
Upvotes: 2