Ivo Ivo - 1 month ago 20
Javascript Question

SideNav from Materializecss stops working in React Web App

I have a simple React App with React-Router and MaterializeCSS for styling.

The SideNav from materialize works at first but when I switch pages, for instance going from root url to url/login it stops working and just adds a hash - url/login# when the menu icon is clicked. It has probably something to do with react-router and browserHistory.

Here's the relevant code for the issue:

firebase.auth().onAuthStateChanged((user) => {
if(user){
browserHistory.push('/');
} else{
}
});

let loginRedirect = (nextState, replace, next) => {
if(firebase.auth().currentUser){
store.dispatch(actions.startLogout());
replace('/');
} else{
next();
}
};

ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={Layout}/>
<Route path="/login" component={Login} onEnter={loginRedirect}/>
</Router>
</Provider>
,app);

$(document ).ready(function(){$('.button-collapse').sideNav({
menuWidth: 200,
edge: 'left',
closeOnClick: true,
draggable: true
}
)});

Answer

jQuery and React are interfering heavily here. You're probably better off using react-material's Drawer component. It is written in React and makes it much easier to implement and maintain. Here's an example from their documentation:

import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import RaisedButton from 'material-ui/RaisedButton';

export default class DrawerUndockedExample extends React.Component {

  constructor(props) {
    super(props);
    this.state = {open: false};
  }

  handleToggle = () => this.setState({open: !this.state.open});

  handleClose = () => this.setState({open: false});

  render() {
    return (
      <div>
        <RaisedButton
          label="Open Drawer"
          onTouchTap={this.handleToggle}
        />
        <Drawer
          docked={false}
          width={200}
          open={this.state.open}
          onRequestChange={(open) => this.setState({open})}
        >
          <MenuItem onTouchTap={this.handleClose}>Menu Item</MenuItem>
          <MenuItem onTouchTap={this.handleClose}>Menu Item 2</MenuItem>
        </Drawer>
      </div>
    );
  }
}

I'd also recommend to switch to Material-UI for all the other stuff you want to build.