|
1 | 1 | import React from 'react'
|
2 | 2 |
|
3 |
| -export default router5LinkFactory |
| 3 | +export default linkFactory |
4 | 4 |
|
5 |
| -let router5LinkFactory = (router) => { |
| 5 | +let linkFactory = (router) => { |
6 | 6 | return React.createClass({
|
7 | 7 | propTypes: {
|
8 | 8 | routeName: React.PropTypes.string.isRequired
|
9 |
| - routeParams: React.PropTypes.object |
10 |
| - routeOptions: React.PropTypes.object |
| 9 | + routeParams: React.PropTypes.object, |
| 10 | + routeOptions: React.PropTypes.object, |
| 11 | + activeClass: React.PropTypes.string, |
| 12 | + onClick: React.PropTypes.func |
11 | 13 | },
|
12 | 14 |
|
| 15 | + getDefaultProps() ({ |
| 16 | + className: '', |
| 17 | + activeClass: 'active', |
| 18 | + routeParams: {}, |
| 19 | + routeOptions: {}, |
| 20 | + onClick: this.clickHandler |
| 21 | + }), |
| 22 | + |
| 23 | + getInitialState() ({ |
| 24 | + // Initialise state |
| 25 | + // Not an anti-pattern |
| 26 | + // https://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html |
| 27 | + active: router.isActive(this.props.routeName, this.prop.routeParams) |
| 28 | + }), |
| 29 | + |
| 30 | + // Is it overkill? |
13 | 31 | shouldComponentUpdate(nextProps, nextState) {
|
14 | 32 | return !router.areStatesEqual(
|
15 | 33 | {name: nextProps.routeName, params: nextProps.routeParams},
|
16 | 34 | {name: this.props.routeName, params: this.props.routeParams}
|
17 |
| - ) |
| 35 | + ) || this.state.active !== nextState.active; |
18 | 36 | },
|
19 | 37 |
|
20 | 38 | clickHandler(evt) {
|
21 | 39 | evt.preventDefault()
|
22 | 40 | router.navigate(this.props.routeName, this.props.routeParams, this.props.options)
|
23 | 41 | },
|
24 | 42 |
|
| 43 | + // Is it overkill? |
| 44 | + // Should it be an option to observe state in Links? |
| 45 | + // Should we add a GroupLink component for menus? |
| 46 | + routeChangeHandler(toState, fromState) { |
| 47 | + this.setState({active: router.isActive(this.props.routeName, this.prop.routeParams)}) |
| 48 | + }, |
| 49 | + |
| 50 | + componentDidMount() { |
| 51 | + router.addListener(this.routeChangeHandler) |
| 52 | + }, |
| 53 | + |
| 54 | + componentWillUnmount() { |
| 55 | + router.removeListener(this.routeChangeHandler) |
| 56 | + } |
| 57 | + |
25 | 58 | render() {
|
26 |
| - let path = router.buildPath(this.props.routeName, this.props.routeParams) |
27 |
| - return <a href={path} onClick={clickHandler}></a> |
| 59 | + let props = this.props |
| 60 | + let active = this.state.active |
| 61 | + |
| 62 | + let path = router.buildPath(this.props.routeName, this.props.routeParams); |
| 63 | + let className = props.className.split(' ') |
| 64 | + .concat(active ? [activeClassName] : []).join(' ') |
| 65 | + |
| 66 | + return <a href={path} className={className} onClick={props.onClick}></a> |
28 | 67 | }
|
29 | 68 | })
|
30 | 69 | }
|
0 commit comments