dark mode

How to use withStyles from Material UI with HOC in React

How to use withStyles from Material UI with HOC in React

Here is a simple React app example using Material UI. The problem I stumbled is how to add JSS withStyles into Higher-Order Components (HOC).

This is react's the index.js file adding simple component called Hello.

import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './hello';

function App() {
  return (
    <div className="App">
      <Hello />
    </div>
  );
}

const rootElement = document.getElementById('root');
ReactDOM.render(<App />, rootElement);

In Hello component hello.js we use Higher-Order Component (HOC) called withBackground. This HOC only adds a background color for simplicity.

import React from 'react';
import withBackground from './withBackground';

const Hello = () => {
  return <h1>Hello Everyone</h1>;
};

export default withBackground(Hello);

Below is the syntax for HOC using withStyles with and without Redux.

withBackground.js with Redux

import React from 'react';
import { compose } from 'redux';
import { withStyles, createStyles } from '@material-ui/core';

const withBackground = WrappedComponent => {
  return class extends React.Component {
    render() {
      const { classes } = this.props;
      return (
        <div className={classes.backgroundColor}>
          <WrappedComponent />
        </div>
      );
    }
  };
};

const styles = () =>
  createStyles({
    backgroundColor: {
      backgroundColor: 'red'
    }
  });

export default compose(
  withStyles(styles),
  withBackground
);

withBackground.js without Redux

import React from 'react';
import { withStyles, createStyles } from '@material-ui/core';

const withBackground = WrappedComponent => {
  const WithBackground = ({ classes }) => {
    return (
      <div className={classes.backgroundColor}>
        <WrappedComponent />
      </div>
    );
  };

  return withStyles(styles)(WithBackground);
};

const styles = () =>
  createStyles({
    backgroundColor: {
      backgroundColor: 'red'
    }
  });

export default withBackground;

Related articles

© 2019 All rights reserved.