score:0
These are good answers. I'm taking notes :) When I first read the post, I suspect the intuition was around using the overrides
key in the built-in MUI theme.
I often find the overrides key a more convenient way to implement a format used "more often" in the app.
It's a two-step process:
- Decide which MUI component you want to modify
- Set the
className
prop using a naming convention that works for you
import clsx from 'clsx'; // not required, but handy in the long-run
import Fab from '@material-ui/core/Fab';
const Component = () => {
...
return <Fab className=clsx('MyCustomFab') />
}
// my theme prop for the MUI <ThemeProvider theme={myTheme} />
export default createMuiTheme({
...
overrides: {
MuiFab: {
root: {
'&.MyCustomFab': { // note: the "no-space" => MuiFab AND ...
backgroundColor: "lightblue",
}
}
}
}
}
score:1
className={this.props.theme.fab}
doesn't work because this.props.theme.fab
is an object, not a class name. When withStyles
is used, it takes care of generating a unique class name (e.g. available via props.classes.fab
) as well as injecting the CSS for that class into the head of the document. The fab
object in your theme has not had this work done for it.
The code below shows a couple ways you can avoid redundant code. The first is a withFab
function that encapsulates the CSS and the call to withStyles
.
The second uses the fab
object more directly and just passes it to the style
property rather than the className
property. You could get the styles from theme.fab
(rather than a separate js file) similar to your initial approach, but there isn't necessarily a reason to put this in your theme unless you care about being able to override it via different MuiThemeProviders
in your rendering hierarchy.
There are a couple downsides to the second (style property) approach:
- If you use this on a lot of different elements, the CSS is redundantly specified in the DOM on each of those elements.
- It won't support CSS that requires classes (e.g. using pseudo elements like :hover)
So I would recommend something more similar to the first option (UseWithFab/withFab
) shown below.
withFab.js
import withStyles from "@material-ui/core/styles/withStyles";
const styles = {
fab: {
backgroundColor: "lightblue"
}
};
export const fabStyles = {
backgroundColor: "lightgreen"
};
const withFab = component => {
return withStyles(styles)(component);
};
export default withFab;
index.js
import React from "react";
import ReactDOM from "react-dom";
import withFab, { fabStyles } from "./withFab";
const UseWithFab = withFab(props => {
return <div className={props.classes.fab}>Using withFab</div>;
});
const UseFabStyles = props => {
return <div style={fabStyles}>Using fabStyles</div>;
};
function App(props) {
return (
<>
<UseWithFab />
<UseFabStyles />
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
score:2
I don't think createMuiTheme
is meant for that.
Alternatively you could just create a style object that you want to reuse
const styles = {
fab: {
position: "relative",
top: 0,
marginTop: 20px
textTransform: 'none',
width: 220,
height: 50
}
};
And just import and use it wherever you need to
import fabStyles from '../../somewhere-everyone-can-get-it.js';
import styles from './styles-for-this-component.js';
...
withStyles({...fabStyles, ...styles})(Component);
If you need the theme and styles.
withTheme(withStyles({...fabStyles, ...styles})(Component));
You can also use recompose
to clean this up.
Source: stackoverflow.com
Related Query
- How do I create css class in createMuiTheme() and use them directly without having to get its value from component "classes" props?
- How to create and use global css variables in jss
- How to Create global styles with Styled components in react and next js and is it better to use combination of css files and styled component?
- how to use css module without modifying class names in react
- how to use backdropFilter in js file and not css without error
- how to create dynamic variables and use them with useState()
- How to create and apply dynamic stylesheet based CSS class in ReactJS?
- How to remove default Button classes from material UI and use my own css class
- How can I use an array map of routes with BrowserRouter and Switch without them all loading at once?
- How can I use one CSS module and adding just another style to it without rewriting the code?
- How can hover image in ReactJs in by CSS file without use onMouseOut and onMouseHover
- How to use vw and vh css with React Native
- How to avoid very long paths and use absolute paths within a Create React App project?
- How to use babel directly from a script tag without installing babel itself
- How to create multiple entries and output for create-react-app and keep them separated?
- How to use scss without css modules in nextjs
- How to use currying to create HoC in React and connect to the Redux store at the same time?
- React and Flex layout how to use them
- How to import svg files and use them for src in image
- Webpack: How to use CSS-modules and imported CSS from outside libraries?
- How to wrap 2 or more menu items to use them in one condition, using React and ant design?
- How can I use Promise.all on an array of objects and then reassign them to the relevant key in a new object?
- How to use Sass and CSS Modules with create-react-app?
- How can we create and returns a 404 page, if someone access pages via url without login
- How to determine the order of css in my create react app build with webpack and customize-cra?
- how to import multiple components as a single component and use them in lazy load
- how to create a class and another classes extends that class in react js
- How to use foundation css with webpack and react?
- How can I toggle a class and change the CSS in Nextjs?
- How to create and use a styled-component that renders {props.children} in Typescript?
More Query from same tag
- Have a communicating variable between two files in React
- Why "gulp-jest" is failing with: "Please run node with the --harmony flag!"?
- Handle an array of inputs -React
- edit text input React
- Activating 2 different calls on react onClick
- How to define, append or map objectID to an array for Algolia?
- Material UI: how do I use Theme values with withStyles?
- Limiting keyboard inputs to A-Z as opposed to any keyboard input on React component
- How to load initial state in a flux store asynchronously?
- Material Ui, MUI, Dialog, ScrollTop
- Unexpected Lines under TextInput in React Native Android App
- How should I avoid this "Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler."
- How can I convert this hook based code to class based code? is it possible?
- Convert Webpack syntax to browserify syntax
- Property 'X' does not exist on type 'IntrinsicAttributes & InferPropsInner
- Unable to get the socket id on the front end
- How to segregate JSON and show the largest number
- validateFieldsAndScroll not working and Cannot read property 'match' of undefined
- Display MONGODB data in React.js page
- Is there any way to change image in tailwindcss when dark mode toggled?
- react-spring, animate list items individually
- React.js How can I convert string base64 to normal image
- React Router: hiding or removing a component on a specific path
- ReactJS - Embed Svg image using D3
- Editable div content
- Error: Type with name "AuthorYaml" does not exists - gatsby-casper starter
- Reactjs: Reusable button component to generate a component provided as a prop
- How to re-render a react component with an input value passed from another component
- React Router content not load when refresh forward or manually input
- Class component: Cannot read property 'user' of undefined