Skip to content

Commit

Permalink
UnitControl: Fix internal unit state/parsing to handle incoming unit …
Browse files Browse the repository at this point in the history
…prop (#23521)

This update fixes the `<UnitControl />` component to handle (new) incoming `unit` prop changes. This is important for handling interactions such as unit swapping - an interaction we have for the Cover block.
  • Loading branch information
Q authored and youknowriad committed Jul 13, 2020
1 parent 84f7682 commit ce8cb5d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
7 changes: 5 additions & 2 deletions packages/components/src/unit-control/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import classnames from 'classnames';
/**
* WordPress dependencies
*/
import { useState, forwardRef } from '@wordpress/element';
import { forwardRef } from '@wordpress/element';

/**
* Internal dependencies
Expand All @@ -19,6 +19,7 @@ import {
import { Root, ValueInput } from './styles/unit-control-styles';
import UnitSelectControl from './unit-select-control';
import { CSS_UNITS, getParsedValue, getValidParsedUnit } from './utils';
import { useControlledState } from '../utils/hooks';

function UnitControl(
{
Expand All @@ -43,7 +44,9 @@ function UnitControl(
ref
) {
const [ value, initialUnit ] = getParsedValue( valueProp, unitProp, units );
const [ unit, setUnit ] = useState( initialUnit );
const [ unit, setUnit ] = useControlledState( unitProp, {
initial: initialUnit,
} );

const classes = classnames( 'components-unit-control', className );

Expand Down
15 changes: 15 additions & 0 deletions packages/components/src/unit-control/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
*/
import { render, unmountComponentAtNode } from 'react-dom';
import { act, Simulate } from 'react-dom/test-utils';
import { render as testRender } from '@testing-library/react';

/**
* WordPress dependencies
Expand Down Expand Up @@ -372,5 +373,19 @@ describe( 'UnitControl', () => {

expect( state ).toBe( '123rem' );
} );

it( 'should update unit after initial render and with new unit prop', () => {
const { container: testContainer, rerender } = testRender(
<UnitControl value={ '10%' } />
);

const select = testContainer.querySelector( 'select' );

expect( select.value ).toBe( '%' );

rerender( <UnitControl value={ state } unit="em" /> );

expect( select.value ).toBe( 'em' );
} );
} );
} );

0 comments on commit ce8cb5d

Please sign in to comment.