fortrustit fortrustit - 1 month ago 4
React JSX Question

activeClassName does not work on the sideMenu when clicking on the link

I have a sidebar menu which imports a child component containing a list of menu items. I want to set the activeClassName to each of the

<Link />
in the child component
<SideMenuContainer />
. However, the active link only works on the page load.

import React, { Component } from 'react';
import SideMenuContainer from './SideMenu/SideMenuContainer';

export default class CompanyInfoMenu extends Component {

constructor() {
super();
this.toggleShow = this.toggleShow.bind(this);
this.state = {
isShow: false,
};
}

toggleShow() {
this.setState({ isShow: !this.state.isShow });
}

render() {
return (
<div>
<ul>
<li>
<span onClick={() => this.toggleShow()}>button</span>
{this.state.isShow ? <ul><SideMenuContainer /></ul> : <div></div>}
</li>
</ul>
</div>
);
}
}


The routing looks like this

<IndexRedirect to="client-info" />
<Route path="client-info" component={ClientInfoSection}>
<IndexRedirect to="BasicInformation" />
<Route path=":itemType" component={ItemContentContainer} />
<Route path="company-introduction" component={CompanyInformationContainer} />
</Route>


When the
:itemType
changes, the activeClassName doesn't apply.

The
<SideMenuContainer />
looks like this

return (
<ul>
<li>
<Link
to={`/client-info/${item.itemType}`}
activeClassName="active"
>
item1
</Link>
</li>
</ul>
);

Answer

This is known bug for dynamic routes in react-router v2.x.x: https://github.com/ReactTraining/react-router/issues/3286

To get the routes work properly you should add { pure: false } to the connect() parameters:

export default connect(mapStateToProps,
                       mapDispatchToProps,
                       null,
                       { pure: false })(SideMenuContainer);
Comments