I'm having an issue where I'm using the styled function to style a custom React component but the styles are not being applied. In the example below, I would expect the Child component to have the color: red style, but it doesn't. The sibling component, however, is styled correctly.
import "./styles.css";
import { Child } from "./Child";
import { Typography } from "#mui/material";
import { styled } from "#mui/material/styles";
const StyledChild = styled(Child)(() => ({
color: "red"
}));
const StyledSibling = styled(Typography)(() => ({
color: "blue"
}));
export default function App() {
return (
<>
<StyledChild />
<StyledSibling>Sibling</StyledSibling>
</>
);
}
import { Typography } from "#mui/material";
import { FunctionComponent } from "react";
export const Child: FunctionComponent = () => {
return <Typography>Child</Typography>;
};
CodeSandbox
styled causes a className prop to be passed to the wrapped component, but Child isn't passing the className prop along to Typography.
Here's an example of how to fix Child.tsx:
import { Typography } from "#mui/material";
import { FunctionComponent } from "react";
export const Child: FunctionComponent<{ className?: string }> = ({
className
}) => {
return <Typography className={className}>Child</Typography>;
};
Related
How can I apply dynamic styling to a styled-component that is being passed to a child component?
Sample/index.js
import React from "react";
import { MainText } from "./styles";
import Child from "./Child";
const Sample = ({ className }) => {
const isCompleted = true;
const checkStatus = isCompleted;
return (
<div className={className}>
<Child MainText={MainText} $checkStatus={checkStatus} />
</div>
);
};
export default Sample;
Sample/styles.js
import styled from "styled-components";
export const MainText = styled.div`
color: ${({ $checkStatus }) => $checkStatus && "red"};
`;
MainText.displayName = "MainText";
How can I pass $checkStatus to MainText styled-component?
How can I pass makeStyle classes from parent component to child component and combine them with the makeStyle classes in the child component? E.g. as below adding the breakpoint hiding to the child component style.
Example child component:
import React from "react"
import { Button } from "#material-ui/core"
import { makeStyles } from "#material-ui/core/styles"
const useStyles = makeStyles(theme => ({
button: {
background: "#000",
color: "white",
//lots of other css here so we dont want to repeat it in the parent component
},
}))
export default function PrimaryButton(props) {
const classes = useStyles()
const { children, fullWidth = false } = props
return (
<Button
fullWidth={fullWidth}
className={classes.button}
variant="contained"
>
{children}
</Button>
)
}
Example parent component:
import React from "react"
import { PrimaryButton } from "components/PrimaryButton"
import { makeStyles } from "#material-ui/core/styles"
const useStyles = makeStyles(theme => ({
primaryButton: {
display: "inline-block",
[theme.breakpoints.down("sm")]: {
display: "none",
},
},
}))
export default function PrimaryButton(props) {
const classes = useStyles()
return (
<PrimaryButton
className={classes.primaryButton}
>
Button text
</PrimaryButton>
)
}
clsx is used internally within Material-UI and is a convenient utility for combining multiple class names. In your child component, you can grab className from the props and then use className={clsx(className, classes.button)} in the Button it renders:
import React from "react";
import { Button } from "#material-ui/core";
import { makeStyles } from "#material-ui/core/styles";
import clsx from "clsx";
const useStyles = makeStyles(theme => ({
button: {
background: "#000",
color: "white"
}
}));
export default function PrimaryButton(props) {
const classes = useStyles();
const { children, className, fullWidth = false } = props;
return (
<Button
fullWidth={fullWidth}
className={clsx(className, classes.button)}
variant="contained"
>
{children}
</Button>
);
}
For some reason my material ui styles are not applying to my html element? Any idea why? I have no other styles applied to this page
import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '#material-ui/core';
const classes = makeStyles( (theme) => ({
root: {
paddingTop: theme.spacing(8),
backgroundColor: "white"
},
}) )
class Login extends Component {
render() {
return(
<div className = {classes.root}>
<LoginForm/>
</div>
);
}
}
export default Login;
In your case, if you want to style your class component, you should use withStyles. Try this:
import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { withStyles } from '#material-ui/core/styles';
const useStyles = (theme) => ({
root: {
paddingTop: theme.spacing(8),
backgroundColor: "white"
},
})
class Login extends Component {
render() {
const { classes } = this.props
return(
<div className = {classes.root}>
<LoginForm/>
</div>
);
}
}
export default withStyles(useStyles)(Login);
makeStyles returns a react hook to use in the component. Hooks also only work in functional components, so you'll need to convert Login to a functional component.
import React, { Component } from 'react';
import LoginForm from '../components/form/loginForm';
import { makeStyles } from '#material-ui/core';
const useStyles = makeStyles(theme => ({
root: {
paddingTop: theme.spacing(8),
backgroundColor: "lightblue"
}
}));
const Login = props => {
const classes = useStyles();
return(
<div className={classes.root}>
<LoginForm/>
</div>
);
}
export default Login;
I want to test a React Component that uses Material-UI`s makeStyles.
My Component:
import React from 'react';
import { useTranslation } from 'react-i18next';
import { DefaultButton } from '../../../../components';
import { makeStyles } from '#material-ui/styles';
const useStyles = makeStyles((theme: any) => ({
root: {},
row: {
marginTop: theme.spacing()
},
spacer: {
flexGrow: 1
},
}));
const UsersToolbar: React.FC<any> = (props) => {
const classes = useStyles();
const { t } = useTranslation();
return (
<div className={classes.root}>
<div className={classes.row}>
<span className={classes.spacer} />
<DefaultButton id="createUserBtn">{t('Create User')}</DefaultButton>
</div>
</div>
);
};
export default UsersToolbar;
My test:
import React from 'react';
import ReactDOM from 'react-dom';
import { createMuiTheme } from '#material-ui/core';
import { ThemeProvider } from '#material-ui/styles';
import UsersToolbar from '.';
describe('<UsersToolbar />', () => {
it('passes smoke test', () => {
const div = document.createElement('div');
ReactDOM.render(
<UsersToolbar />,
div
);
});
});
I was thinking about using jest.mock() and place a manual mock in __mocks__/
How can I do that? I tried to provide a ThemeProvider as proposed on the official Material-UI homepage (https://material-ui.com/guides/testing/) but it did not work out.
I solved this by creating a component named MockTheme which wraps the component that needs to be tested. The result looks like the following:
import React from 'react';
import { createMuiTheme } from '#material-ui/core';
import { ThemeProvider } from '#material-ui/core/styles';
function MockTheme({ children }: any) {
const theme = createMuiTheme({});
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
}
export default MockTheme;
The modified test now works:
import React from 'react';
import ReactDOM from 'react-dom';
import MockTheme from '../../../../theme/MockTheme';
import UsersToolbar from '.';
describe('<UsersToolbar />', () => {
it('passes smoke test', () => {
const div = document.createElement('div');
ReactDOM.render(
<MockTheme>
<UsersToolbar />
</MockTheme>,
div
);
});
});
can you please help me to change the React Material UI theme Dynamically .
https://imgur.com/S8zsRPQ
https://imgur.com/Ul8J40N
I have tried by changing the theme Properties on button click . The theme properties are getting changed as seen in the console . But the change is not reflecting on the theme .
Sandbox Code : https://codesandbox.io/s/30qwyk92kq
const themeChange = () => {
alert(theme);
theme.palette.type = "light";
console.log(theme);
};
ReactDOM.render(
<MuiThemeProvider theme={theme}>
<React.Fragment>
<CssBaseline />
<App changeTheme={themeChange} />
</React.Fragment>
</MuiThemeProvider>,
document.getElementById("app")
);
When I click the button the theme has to change to Dark color
I am using styledComponents, typescript and material-ui.
First I defined my themes:
// This is my dark theme: dark.ts
// I defined a light.ts too
import createMuiTheme from '#material-ui/core/styles/createMuiTheme';
export const darkTheme = createMuiTheme({
palette: {
type: 'dark', // Name of the theme
primary: {
main: '#152B38',
},
secondary: {
main: '#65C5C7',
},
contrastThreshold: 3,
tonalOffset: 0.2,
},
});
I defiend a themeProvider function and in this function I wrapped the material-ui's ThemeProvider in a React context to be able to change the theme easily:
import React, { useState } from 'react';
import {ThemeProvider} from "#material-ui/core/styles/";
import { lightTheme } from "./light";
import { darkTheme } from "./dark";
const getThemeByName = (theme: string) => {
return themeMap[theme];
}
const themeMap: { [key: string]: any } = {
lightTheme,
darkTheme
};
export const ThemeContext = React.createContext(getThemeByName('darkTheme'));
const ThemeProvider1: React.FC = (props) => {
// State to hold the selected theme name
const [themeName, _setThemeName] = useState('darkTheme');
// Retrieve the theme object by theme name
const theme = getThemeByName(themeName);
return (
<ThemeContext.Provider value={_setThemeName}>
<ThemeProvider theme={theme}>{props.children}</ThemeProvider>
</ThemeContext.Provider>
);
}
export default ThemeProvider1;
Now I can use it in my components like this:
import React from 'react';
import styled from 'styled-components';
import useTheme from "#material-ui/core/styles/useTheme";
const MyCardHeader = styled.div`
width: 100%;
height: 40px;
background-color: ${props => props.theme.bgColor};
color: ${props => props.theme.txtColor};
display: flex;
align-items:center;
justify-content: center;
`;
export default function CardHeader(props: { title: React.ReactNode; }) {
const theme = {
bgColor: useTheme().palette.primary.main,
txtColor: useTheme().palette.primary.contrastText
};
return (
<MyCardHeader theme={theme}>
{props.title}
</MyCardHeader>
);
}
For Changing between themes:
import React, {useContext} from 'react';
import { ThemeContext} from './themes/themeProvider';
export default function Header() {
// Get the setter function from context
const setThemeName = useContext(ThemeContext);
return (
<header>
<button onClick={() => setThemeName('lightTheme')}>
light
</button>
<button onClick={() => setThemeName('darkTheme')}>
dark
</button>
</header>
);
}
I'm using Material UI v4.
I tried something like Ashkan's answer, but it didn't work for me.
However, I found this in the documentation, and abstracting it to apply to a different piece of state, instead of user preference, worked for me. For your example, I'd probably make a context:
// context.js
import React, { useContext } from "react";
import { ThemeProvider, createTheme } from "#material-ui/core/styles";
import CssBaseline from "#material-ui/core/CssBaseline";
const CustomThemeContext = React.createContext();
// You can add more to these and move them to a separate file if you want.
const darkTheme = {
palette: {
type: "dark",
}
}
const lightTheme = {
palette: {
type: "light",
}
}
export function CustomThemeProvider({ children }) {
const [dark, setDark] = React.useState(false);
function toggleTheme() {
if (dark === true) {
setDark(false);
} else {
setDark(true);
}
}
const theme = React.useMemo(
() => {
if (dark === true) {
return createTheme(darkTheme);
}
return createTheme(lightTheme);
},
[dark],
);
return (
<CustomThemeContext.Provider value={toggleTheme}>
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
</CustomThemeContext.Provider>
);
}
export function useToggleTheme() {
const context = useContext(CustomThemeContext);
if (context === undefined) {
throw new Error("useCustomThemeContext must be used within an CustomThemeProvider");
}
return context;
}
Then wrap your app in that:
ReactDOM.render(
<CustomThemeProvider>
<App />
</CustomThemeProvider>,
document.getElementById("app")
);
And then access it in your app:
export default function App(){
const toggleTheme = useToggleTheme();
return (
<div>
<button onClick={toggleTheme}>Toggle the theme!!</button>
</div>
);
}
On a side note, in my app, I actually have a different theme in two sections of the app, based on whether the user is logged in or not. So I'm just doing this:
function App() {
const { authState } = useAuthContext();
const theme = React.useMemo(
() => {
if (authState.user) {
return createTheme(dashboardTheme);
}
return createTheme(loginTheme);
},
[authState.user],
);
return (
<ThemeProvider theme={theme}>
<TheRestOfTheApp />
</ThemeProvider>
}
It seems you can base the theme off any piece of state, or multiple pieces, by referencing them in useMemo and including them in the dependency array.
EDIT:
I just noticed that MUI v5 actually has something very similar in their docs.
In your code, theme type is changed. But the Page is not re-rendered with new theme.
I have changed code in index.js and App.js like following.
Try this approach. It works.
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
ReactDOM.render(
<App/>,
document.getElementById("app")
);
App.js
import React from "react";
import CssBaseline from "#material-ui/core/CssBaseline";
import Typography from "#material-ui/core/Typography";
import { Button } from "#material-ui/core";
import { MuiThemeProvider, createMuiTheme } from "#material-ui/core/styles";
import blueGrey from "#material-ui/core/colors/blueGrey";
import lightGreen from "#material-ui/core/colors/lightGreen";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
themeType : 'dark',
}
}
changeTheme(){
if (this.state.themeType == 'dark'){
this.setState({themeType:'light'});
} else {
this.setState({themeType:'dark'});
}
}
render() {
let theme = createMuiTheme({
palette: {
primary: {
light: lightGreen[300],
main: lightGreen[500],
dark: lightGreen[700]
},
secondary: {
light: blueGrey[300],
main: blueGrey[500],
dark: blueGrey[700]
},
type: this.state.themeType
}
});
return (
<MuiThemeProvider theme={theme}>
<CssBaseline />
<Typography>Hi there!</Typography>
<Button
variant="contained"
color="secondary"
onClick={()=>{this.changeTheme()}}
>
Change
</Button>
</MuiThemeProvider>
);
}
}
export default App;