I want to set the value of a field based on what I have in the database. Make it in-editable but also want the ability for customers to copy that value.
I am able to set the form field values now- but I am unable to use the copy clipboard feature.
const APIAccess = ({product_id}) => {
const [form] = Form.useForm();
const dbvalues = "adsd";
const clientIdRef = useRef();
const [isCopied, setIsCopied] = useState(false);
const {
token: { colorBgContainer },
} = theme.useToken();
const copyClientId = () => {
const clientId = clientIdRef.current.value;
navigator.clipboard.writeText(clientId);
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 1000);
};
return (
<Form
name="control-hooks"
initialValues={{
clientID: dbvalues,}}
form={form}
>
<Form.Item
label="Your Client ID"
name="clientID"
ref={clientIdRef}
>
<Space>
<Input type="text" value={dbvalues} />
<Tooltip title="copy your Client ID">
<Button icon={isCopied ? <CheckSquareOutlined /> : <CopyOutlined />} onClick={copyClientId} /> </Tooltip>
</Space>
</Form.Item>
<Form.Item
label="Your Client Secret"
name="clientSecret"
>
</Form>
);
}
You don't want to programmatically set each initial value. Instead, pass all the initial values to the Form component:
<Form
initialValues={{
clientID: some_client_id,
}}
/>
As for copying the value of the input field to the clipboard, use the useForm()
hook provided by antd.
import React, { useRef, useState } from "react";
import { Button, Form, Input } from "antd";
import { CopyOutlined, CheckSquareOutlined } from "@ant-design/icons";
export default function App() {
const [form] = Form.useForm();
const [isCopied, setIsCopied] = useState(false);
const copyClientId = () => {
const clientId = form.getFieldValue("clientId");
navigator.clipboard.writeText(clientId);
setIsCopied(true);
setTimeout(() => {
setIsCopied(false);
}, 1000);
};
return (
<>
<Form
form={form}
name="basic"
labelCol={{ span: 8 }}
wrapperCol={{ span: 16 }}
style={{ maxWidth: 600 }}
initialValues={{
clientId: "9834fh3fh439f348hf94",
}}
>
<Form.Item label="Client ID" name="clientId">
<Input />
</Form.Item>
<Form.Item wrapperCol={{ offset: 8, span: 16 }}>
<Button
type="primary"
htmlType="button"
icon={isCopied ? <CheckSquareOutlined /> : <CopyOutlined />}
onClick={copyClientId}
>
Copy
</Button>
</Form.Item>
</Form>
</>
);
}
Be sure to pass form
as a prop to the <Form>
component.
I added the icon change as a bonus! You always want to indicate to the user that an action has taken place.