Skip to content

Instantly share code, notes, and snippets.

@davidfurlong
Created June 1, 2018 10:31
Show Gist options
  • Save davidfurlong/ab257a96d14c6582ff2d9bffc40926b7 to your computer and use it in GitHub Desktop.
Save davidfurlong/ab257a96d14c6582ff2d9bffc40926b7 to your computer and use it in GitHub Desktop.
Ant design + RR4 Routed Tabs
<RoutedTabs>
<TabPane
key={1}
to={`/about`}
tab={t('about')}
>
<Route
path={`/about`}
component={About}
/>
</TabPane>
<TabPane
key={2}
to={`/contact`}
tab={t('contact')}
>
<Route
path={`/contact`}
component={Contact}
/>
</TabPane>
</RoutedTabs>
import React from 'react';
import { Tabs } from 'antd';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
const propTypes = {
history: PropTypes.any,
location: PropTypes.any,
action: PropTypes.oneOf(['push', 'replace']).isRequired,
// onClick: PropTypes.func,
// active: PropTypes.bool,
// target: PropTypes.string,
children: PropTypes.node.isRequired,
};
const defaultProps = {
action: 'push',
};
class RoutedTabs extends React.Component {
static propTypes = propTypes;
static defaultProps = defaultProps;
// returns [activeKey, children]
generateChildren = () => {
let activeKey = null;
const children = React.Children.map(this.props.children, child => {
if (!child) return null;
const [pathname] = child.props.to.split('?');
if (this.props.location.pathname === pathname) {
activeKey = '.$' + child.key.toString();
}
return React.cloneElement(child, { to: undefined });
});
return [activeKey, children];
};
onChange = key => {
const childkey = key.substring(2);
let route;
React.Children.forEach(this.props.children, child => {
if (child && child.key.toString() === childkey) route = child.props.to;
});
if (route) this.props.history.push(route, { resetScroll: false });
};
render() {
const [activeKey, childs] = this.generateChildren();
return (
<Tabs activeKey={activeKey} onChange={this.onChange}>
{childs}
</Tabs>
);
}
}
export default withRouter(RoutedTabs);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment