Asking
Asking

Reputation: 4192

Get a value clicking on a button

In my application i try to get a value from a form tag. This is the component where i want to output the value:

import React, { useState } from "react";

import { Form, Input, Button, Space } from "antd";
import { PlusOutlined } from "@ant-design/icons";

const Inner = props => {
  const [formVal, setFormVal] = useState([]);
  const [defaultMode, setDefaultMode] = useState(true);

  const onFinish = values => {
    setFormVal(values);
    console.log("Received values of form:", values);
  };

  const setFieldOnEdit = index => () => {
    console.log("index", index);
  };

  return (
    <Form.List onFinish={onFinish} name={[props.fieldKey, "inner"]}>
      {(fields, { add, remove }) => {
        return (
          <div>
            {fields.map((field, index) => (
              <Space
                key={field.key}
                style={{ display: "flex", marginBottom: 8 }}
                align="start"
              >
                <Form.Item
                  {...field}
                  name={[field.name, "first"]}
                  fieldKey={[field.fieldKey, "first"]}
                  rules={[{ required: true, message: "Missing first name" }]}
                >
                  <Input placeholder="First Name" />
                </Form.Item>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    Submit inner{setFieldOnEdit(index)}
                  </Button>
                </Form.Item>
              </Space>
            ))}

            <Form.Item>
              <Button
                type="dashed"
                onClick={() => {
                  add();
                }}
                block
              >
                <PlusOutlined /> Add field to inner
              </Button>
            </Form.Item>
          </div>
        );
      }}
    </Form.List>
  );
};
export default Inner;

Now the submit button from form works ok when i click on:

  <Button type="primary" htmlType="submit">
    Submit inner{setFieldOnEdit(index)}
  </Button>

But i want, when i click on this button, to trigger and setFieldOnEdit(index) function, and to get inside:

  const setFieldOnEdit = index => () => {
    console.log("index", index); //here i want to get the index when i click on  the button
  };

... the index. But when i click on the button, i just submit the form, but not trigger the setFieldOnEdit() function.
How to trigger the function and to get the index inside the above function?
demo: https://codesandbox.io/s/aged-architecture-0r2si?file=/InnerForm.js

Upvotes: 0

Views: 44

Answers (1)

dabo248
dabo248

Reputation: 3437

You can call setFieldOnEdit(index) with the Buttons' onClick property:

<Button type="primary" htmlType="submit" onClick={setFieldOnEdit(index)}>
    Submit inner
</Button>

Upvotes: 1

Related Questions