From 4bfcda95eaf44caa98fd3f3df782428b824f93e6 Mon Sep 17 00:00:00 2001 From: Patrick Villanueva Date: Sat, 6 Jun 2020 01:43:17 +0800 Subject: [PATCH] Use React hooks for TabPanel component (#22906) * Use React hooks for TabPanel component * Use hook for instanceId * Fix instanceId and use template literals Co-authored-by: Patrick Villanueva --- packages/components/src/tab-panel/index.js | 136 +++++++++------------ 1 file changed, 59 insertions(+), 77 deletions(-) diff --git a/packages/components/src/tab-panel/index.js b/packages/components/src/tab-panel/index.js index 682ac3fcfe1029..8ca38e19927b0d 100644 --- a/packages/components/src/tab-panel/index.js +++ b/packages/components/src/tab-panel/index.js @@ -7,8 +7,8 @@ import { partial, noop, find } from 'lodash'; /** * WordPress dependencies */ -import { Component } from '@wordpress/element'; -import { withInstanceId } from '@wordpress/compose'; +import { useState } from '@wordpress/element'; +import { useInstanceId } from '@wordpress/compose'; /** * Internal dependencies @@ -29,87 +29,69 @@ const TabButton = ( { tabId, onClick, children, selected, ...rest } ) => ( ); -class TabPanel extends Component { - constructor() { - super( ...arguments ); - const { tabs, initialTabName } = this.props; +export default function TabPanel( { + className, + children, + tabs, + initialTabName, + orientation = 'horizontal', + activeClass = 'is-active', + onSelect = noop, +} ) { + const instanceId = useInstanceId( TabPanel, 'tab-panel' ); + const [ selected, setSelected ] = useState( + initialTabName || ( tabs.length > 0 ? tabs[ 0 ].name : null ) + ); - this.handleClick = this.handleClick.bind( this ); - this.onNavigate = this.onNavigate.bind( this ); - - this.state = { - selected: - initialTabName || ( tabs.length > 0 ? tabs[ 0 ].name : null ), - }; - } - - handleClick( tabKey ) { - const { onSelect = noop } = this.props; - this.setState( { - selected: tabKey, - } ); + const handleClick = ( tabKey ) => { + setSelected( tabKey ); onSelect( tabKey ); - } + }; - onNavigate( childIndex, child ) { + const onNavigate = ( childIndex, child ) => { child.click(); - } - - render() { - const { selected } = this.state; - const { - activeClass = 'is-active', - className, - instanceId, - orientation = 'horizontal', - tabs, - } = this.props; + }; - const selectedTab = find( tabs, { name: selected } ); - const selectedId = instanceId + '-' + selectedTab.name; + const selectedTab = find( tabs, { name: selected } ); + const selectedId = `${ instanceId }-${ selectedTab.name }`; - return ( -
- - { tabs.map( ( tab ) => ( - + + { tabs.map( ( tab ) => ( + - { tab.title } - - ) ) } - - { selectedTab && ( -
- { this.props.children( selectedTab ) } -
- ) } -
- ); - } + { tab.title } + + ) ) } + + { selectedTab && ( +
+ { children( selectedTab ) } +
+ ) } + + ); } - -export default withInstanceId( TabPanel );