I have a InspectorControls
component which include FormTokenField
and I want to pass a ref to FormTokenField
from parent component. In parent I have a button with onClick
handle which will set focus to the field when button is clicked. To make this thing happen I’ve use forwardRef
.
But I get following error message: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
Check the render method of ForwardRef(ChildComponent)
.
Here’s a example how my code looks like:
Parent component:
import ChildComponent from './child-component';
import { Fragment, useRef } from '@wordpress/element';
import { Button } from '@wordpress/components';
import { InspectorControls } from '@wordpress/block-editor';
const ParentComponent = ( { isSelected, ...props } ) => {
const tokenFieldRef = useRef( null );
const clickHandler = () => {
tokenFieldRef.current.focus();
};
return (
<Fragment>
{ isSelected && (
<InspectorControls>
<ChildComponent
{ ...props }
ref={ tokenFieldRef }
/>
</InspectorControls>
) }
<Button
isLink
onClick={ () => clickHandler }
>
Click to focus field
</Button>
// ... here are other child components
</Fragment>
)
}
export default ParentComponent;
Child Component:
import { __ } from '@wordpress/i18n';
import {
PanelBody,
FormTokenField,
} from '@wordpress/components';
import { forwardRef } from '@wordpress/element';
const suggestions = (
__( 'Suggestion one', 'text-domain' ),
__( 'Suggestion two', 'text-domain' ),
);
const ChildComponent = ( props, ref ) => {
const {
attributes,
setAttributes,
} = props;
const { someValue } = attributes;
return (
<PanelBody
className="child-component-settings"
initialOpen={ true }
>
<FormTokenField
ref={ ref }
label={ __( 'Label text', 'text-domain' ) }
value={ someValue }
suggestions={ suggestions }
onChange={ ( newValue ) => setAttributes( { someValue: newValue } ) }
/>
</PanelBody>
);
};
export default forwardRef( ChildComponent );