Search code examples
javascriptformsantd

can't set field value Input antd javascript/reactjs


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;

Solution

  • 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.