1

I have function when click button it will generate password and set value for Input, but when i add field name="password" in the Form.Item it can't work

import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Input, Form, Button } from "antd";
 const App = () => {
  const [generatePW, setGeneratePW] = useState("");

  //Generate Password
  const generatePassword = () => {
    let length = 10;
    let charset =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let retVal = "";
    for (let i = 0, n = charset.length; i < length; ++i) {
      retVal += charset.charAt(Math.random() * n);
    }
    setGeneratePW(retVal);
  };

  const onFinish = (values) => {
    console.log(values);
  };

  return (
    <div>
      <Form onFinish={onFinish}>
        <Form.Item name="password">
          <Input.Password placeholder="Basic usage" value={generatePW} />
        </Form.Item>
        <Button onClick={generatePassword}>Click</Button>
      </Form>
    </div>
  );
};
export default App;
2

1 Answer 1

2

You need to set fields prop of Form like fields={[{ name: "password", value: generatePW }]} in order to manage the state externally. Your final code will be like this:

import React, { useState } from "react";
import "antd/dist/antd.css";
import "./index.css";
import { Input, Form, Button } from "antd";
const App = () => {
  const [generatePW, setGeneratePW] = useState("");

  //Generate Password
  const generatePassword = () => {
    let length = 10;
    let charset =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let retVal = "";
    for (let i = 0, n = charset.length; i < length; ++i) {
      retVal += charset.charAt(Math.random() * n);
    }
    setGeneratePW(retVal);
  };

  const onFinish = (values) => {
    console.log(values);
  };

  return (
    <div>
      <Form
        fields={[{ name: "password", value: generatePW }]}
        onFinish={onFinish}
      >
        <Form.Item name="password">
          <Input.Password
            value={generatePW}
            onChange={(e) => setGeneratePW(e.target.value)}
          />
        </Form.Item>
        <Button onClick={generatePassword}>Click</Button>
      </Form>
    </div>
  );
};
export default App;

You can take a look at this StackBlitz for a live working example of this solution.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.