Skip to content

Commit

Permalink
Fix error triggered when a tab is removed from TabPanel component (#2…
Browse files Browse the repository at this point in the history
  • Loading branch information
youknowriad committed Jul 8, 2020
1 parent d5f9cb7 commit 0fa5f92
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
18 changes: 12 additions & 6 deletions packages/components/src/tab-panel/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { partial, noop, find } from 'lodash';
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
import { useState, useEffect } from '@wordpress/element';
import { useInstanceId } from '@wordpress/compose';

/**
Expand Down Expand Up @@ -39,9 +39,7 @@ export default function TabPanel( {
onSelect = noop,
} ) {
const instanceId = useInstanceId( TabPanel, 'tab-panel' );
const [ selected, setSelected ] = useState(
initialTabName || ( tabs.length > 0 ? tabs[ 0 ].name : null )
);
const [ selected, setSelected ] = useState( null );

const handleClick = ( tabKey ) => {
setSelected( tabKey );
Expand All @@ -51,9 +49,17 @@ export default function TabPanel( {
const onNavigate = ( childIndex, child ) => {
child.click();
};

const selectedTab = find( tabs, { name: selected } );
const selectedId = `${ instanceId }-${ selectedTab.name }`;
const selectedId = `${ instanceId }-${ selectedTab?.name ?? 'none' }`;

useEffect( () => {
const newSelectedTab = find( tabs, { name: selected } );
if ( ! newSelectedTab ) {
setSelected(
initialTabName || ( tabs.length > 0 ? tabs[ 0 ].name : null )
);
}
}, [ tabs ] );

return (
<div className={ className }>
Expand Down
19 changes: 13 additions & 6 deletions packages/components/src/tab-panel/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,12 @@ describe( 'TabPanel', () => {
},
};

const wrapper = TestUtils.renderIntoDocument(
getTestComponent( TabPanel, props )
);
let wrapper;
TestUtils.act( () => {
wrapper = TestUtils.renderIntoDocument(
getTestComponent( TabPanel, props )
);
} );

const alphaTab = getElementByClass( wrapper, 'alpha' );
const betaTab = getElementByClass( wrapper, 'beta' );
Expand Down Expand Up @@ -162,9 +165,13 @@ describe( 'TabPanel', () => {
);
},
};
const wrapper = TestUtils.renderIntoDocument(
getTestComponent( TabPanel, props )
);

let wrapper;
TestUtils.act( () => {
wrapper = TestUtils.renderIntoDocument(
getTestComponent( TabPanel, props )
);
} );

const getActiveTab = () => getElementByClass( wrapper, 'active-tab' );
expect( getActiveTab().innerHTML ).toBe( 'Beta' );
Expand Down

0 comments on commit 0fa5f92

Please sign in to comment.