change Tabs to use react hooks

This commit is contained in:
HF 2021-03-17 14:25:17 +01:00
parent 45e6d15fb3
commit c2bf474136
2 changed files with 46 additions and 85 deletions

View File

@ -1,36 +1,20 @@
import React, { Component } from 'react'; import React from 'react';
class Tab extends Component { const Tab = ({ onClick, activeTab, label }) => {
onClick = () => { let className = 'tab-list-item';
const { label, onClick } = this.props; if (activeTab === label) {
onClick(label); className += ' tab-list-active';
} }
render() { return (
const { <li
onClick, role="presentation"
props: { className={className}
activeTab, onClick={() => onClick(label)}
label, >
}, {label}
} = this; </li>
);
let className = 'tab-list-item'; };
if (activeTab === label) {
className += ' tab-list-active';
}
return (
<li
role="presentation"
className={className}
onClick={onClick}
>
{label}
</li>
);
}
}
export default Tab; export default Tab;

View File

@ -1,62 +1,39 @@
import React, { Component } from 'react'; import React, { useState } from 'react';
import Tab from './Tab'; import Tab from './Tab';
class Tabs extends Component { const Tabs = ({ children }) => {
constructor(props) { const [activeTab, setActiveTab] = useState(children[0].props.label);
super(props);
const { children } = this.props; return (
this.state = { <div className="tabs">
activeTab: children[0].props.label, <ol className="tab-list">
}; {children.map((child) => {
} if (!child.props) {
return undefined;
}
const { label } = child.props;
onClickTabItem = (tab) => { return (
this.setState({ activeTab: tab }); <Tab
} activeTab={activeTab}
key={label}
render() { label={label}
const { onClick={(tab) => setActiveTab(tab)}
onClickTabItem, />
props: { );
children, })}
}, </ol>
state: { <div className="tab-content">
activeTab, {children.map((child) => {
}, if (!child.props || child.props.label !== activeTab) {
} = this; return undefined;
}
return ( return child.props.children;
<div className="tabs"> })}
<ol className="tab-list">
{children.map((child) => {
if (!child.props) {
return undefined;
}
const { label } = child.props;
return (
<Tab
activeTab={activeTab}
key={label}
label={label}
onClick={onClickTabItem}
/>
);
})}
</ol>
<div className="tab-content">
{children.map((child) => {
if (!child.props || child.props.label !== activeTab) {
return undefined;
}
return child.props.children;
})}
</div>
</div> </div>
); </div>
} );
} };
export default Tabs; export default Tabs;