3

I have created a custom <GoogleMap /> component (wrapper for react-google-map) which returns the latitude, longitude and zoomlevel on onClick event of the GoogleMap component. Now I want to wrap it up with the ant.design Form.Item component with the form.getFieldDecorator but can't find a way to do it? All I could do is

<Form.Item label="Point a location">
   {
     form.getFieldDecorator('map', {
       valuePropName: 'onClick',
       getValueFromEvent: mapData => {
        console.log('mapData', mapData);
        return mapData;
       }
     })(
       <div>
         <GoogleMap onClick={data => { console.log('Passed data to parent', data); }} />
       </div>
     )}
</Form.Item>

The on click event does log into the console but doesn't set the value or call the getValueFromEvent function. Any help is appreciated.

acesmndr
  • 8,137
  • 3
  • 23
  • 28

1 Answers1

0

You want Form to control your component (GoogleMap).

In such a case, you need a controlled component, you should implement such a component and let Form to pass a reference to it.

For example with function component, you use forwardRef.

You should read very carefully the getFieldDecorator documentation, in the code you provided, using onClick clearly not makes your component a controlled one, and so it overrides Form attempts to call onClick events.

In simple words: implement a controlled component and define options parameters to tell Form how he should control your component.

In the next example, ControlledComponent behaves like GoogleMaps, and Select component has value and onChange attributes as defaults, such behavior allows Form to update its values (check logs after a click on submit)

function App({ form }) {
  const { getFieldDecorator, validateFields } = form;

  const RefComponent = React.forwardRef((props, ref) => (
    <ControlledComponent {...props} ref={ref} />
  ));

  const onSubmit = e => {
    e.preventDefault();
    validateFields((err, values) => {
      console.log(values);
    });
  };

  return (
    <FlexBox>
      <Form onSubmit={onSubmit}>
        <Form.Item>
          {getFieldDecorator('map', {
            initialValue: 'hello'
          })(<RefComponent />)}
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </FlexBox>
  );
}

export default Form.create({})(App);

Edit Q-57679674-ControlledComponent

Dennis Vash
  • 50,196
  • 9
  • 100
  • 118