Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use useStyle to style Class Component in Material Ui

I want to use useStyle to style the Class Component . But this can be easily done hooks. but i want to use Component instead. But I cant figure out how to do this.

import React,{Component} from 'react'; import Avatar from '@material-ui/core/Avatar'; import { makeStyles } from '@material-ui/core/styles'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined';       const useStyles = makeStyles(theme => ({       '@global': {         body: {           backgroundColor: theme.palette.common.white,         },       },       paper: {         marginTop: theme.spacing(8),         display: 'flex',         flexDirection: 'column',         alignItems: 'center',       },       avatar: {         margin: theme.spacing(1),         backgroundColor: theme.palette.secondary.main,       } }));  class SignIn extends Component{   const classes = useStyle(); // how to assign UseStyle   render(){      return(     <div className={classes.paper}>     <Avatar className={classes.avatar}>       <LockOutlinedIcon />     </Avatar>     </div>   } } export default SignIn; 
like image 683
Jamith NImantha Avatar asked Jun 12 '19 04:06

Jamith NImantha


People also ask

Can we use makeStyles in class component?

In order to use makeStyles function in your application you will need to import it in the component in where you plan to access the css that results from your makeStyles function. This is assuming you have already installed Material Ui in your project. This is in order for react to recognize it as a styles file.

How do you use Usestyle in React?

Styling using CSS file – To style the React elements using the CSS file, we first import the CSS file and then assign the classes contained in the CSS file to the className prop of React elements. Syntax: The syntax to assign the classes to the className prop is mentioned below. Filename: App. js The content of App.


1 Answers

You can do it like this:

import { withStyles } from "@material-ui/core/styles";  const styles = theme => ({   root: {     backgroundColor: "red"   } });  class ClassComponent extends Component {   state = {     searchNodes: ""   };    render() {     const { classes } = this.props;     return (       <div className={classes.root}>Hello!</div>     );   } }  export default withStyles(styles, { withTheme: true })(ClassComponent); 

Just ignore the withTheme: true if you aren't using a theme.


To get this working in TypeScript, a few changes are needed:

import { createStyles, withStyles, WithStyles } from "@material-ui/core/styles";  const styles = theme => createStyles({   root: {     backgroundColor: "red"   } });  interface Props extends WithStyles<typeof styles>{ }  class ClassComponent extends Component<Props> {  // the rest of the code stays the same 
like image 188
Vicente Avatar answered Sep 18 '22 08:09

Vicente