Skip to content

Instantly share code, notes, and snippets.

@roblingle
Last active August 4, 2016 18:09
Show Gist options
  • Save roblingle/0b2e68f31364d820a9fb9dcb0e2418a4 to your computer and use it in GitHub Desktop.
Save roblingle/0b2e68f31364d820a9fb9dcb0e2418a4 to your computer and use it in GitHub Desktop.
MuiThemeWrapper
/*
* MuiThemeWrapper.js
*
* Simplifies Material-UI React components when you don't have a single top-level component,
* which is common in Rails and Meteor where you're including components in pages as needed.
*
*/
import React, { Component } from 'react';
import {deepOrange500} from 'material-ui/styles/colors';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const muiTheme = getMuiTheme({
palette: {
accent1Color: deepOrange500
},
});
// See https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775
export var MuiThemeWrapper = ComposedComponent => class extends Component {
// componentDidMount(){
// console.log('Mounted and enhanced!');
// }
render(){
return (
<MuiThemeProvider muiTheme={muiTheme}>
<ComposedComponent {...this.props} />
</MuiThemeProvider>
);
}
}
@roblingle
Copy link
Author

roblingle commented Aug 4, 2016

Then wrap components when registering for Rails in react_webpack_rails:

import { MuiThemeWrapper } from './components/MuiThemeWrapper';

import Table from './components/Table';
R.registerComponent('Table', MuiThemeWrapper(Table));

This is to avoid re-defining the theme for each component called into the page via:

<%= react_component('Table', { data: @groups }) %>

And without doing that, you'd get a lot of these:

warning.js?8a56:44 Warning: Failed context type: Required context `muiTheme` was not specified in `Table`.

@roblingle
Copy link
Author

roblingle commented Aug 4, 2016

For non-Rails applications, like Meteor, import MuiThemeWrapper as above into each top-level component and export as

export default MuiWrapper(MyComponent);

@roblingle
Copy link
Author

roblingle commented Aug 4, 2016

import React from 'react';
import { Table, TableRow, TableRowColumn } from 'material-ui/Table';

class componentName extends React.Component {
  render () {
    return (
      <Table selectable={true}>
          { this.props.data.map( (row, index) => {
            <TableRow key={index} selected={row.selected}>
              <TableRowColumn>{index}</TableRowColumn>
              <TableRowColumn>{row.name}</TableRowColumn>
            </TableRow>
          } 
        )}
      </Table>
    )
  }
}

Table.propTypes = {
  data: React.PropTypes.arrayOf(React.PropTypes.object).isRequired
}

export default MuiWrapper(componentName);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment