Search code examples
wordpresswordpress-gutenberggutenberg-blocks

Passing value from select control to function


I have create a select control that has a default option and a number of different options which should allow me to style a heading in a number of different ways.

I can see my select changing value(note the console.log) so I know it's working fine.

const MySelectControl = withState( {
   size: 'display-2',
} )( ( { size, setState } ) => (
   <SelectControl
   label="Size"
   value={ size }
   options={ [
       { label: 'Display 1', value: 'display-1' },
       { label: 'Display 2', value: 'display-2' },
       { label: 'Display 3', value: 'display-3' },
       { label: 'Display 4', value: 'display-4' },
   ] }
   onChange={ ( size ) => { setState( { size }, console.log(size + ' from func')  ) } }
   />
) );

// Block Options
const withInspectorControls =  createHigherOrderComponent( ( BlockEdit ) => {


   return (props) => {
       return (
           <Fragment>
           <BlockEdit { ...props } />
           <InspectorControls>
           <PanelBody
           title="Display Block Settings"
           initialOpen={ true }
           >

           <MySelectControl />

           </PanelBody>
           </InspectorControls>
           </Fragment>
       );
   };
}, "withInspectorControl" );

wp.hooks.addFilter( 'editor.BlockEdit', 'display-heading/with-inspector-controls', withInspectorControls );


function handleSize(){
   return MySelectControl.value;
}


const sizeH = handleSize();

I have created a function that handles the value however when I try to return the value in the function handlesize 'return MySelectControl.value', my result is undefined rather than display-2 or any other option.

I can't seem to be able to get the value what am I missing.


Solution

  • I managed to solve this by doing this: -

    1. Create a select control in the edit function.
    {
    
      <SelectControl
          label="Size"
          value={ size }
          options={ [
              { label: 'Display 1', value: 'display-1' },
              { label: 'Display 2', value: 'display-2' },
              { label: 'Display 3', value: 'display-3' },
              { label: 'Display 4', value: 'display-4' },
          ] }
       onChange={ ( size ) => props.setAttributes( { size: size } ) }
          />
    
    }
    
    1. Create an attribute (size)
    2. Change the select control to change the size attribute
    3. Pass the props to the save function props.attributes.size