It supposed to add the student list when I click on the button, but it doesn't.
It should be like the pict below:
I already check my code, and here it is:
import React from "react";
import './App.css';
import "antd/dist/antd.css";
import { Form, Input, Button } from "antd";
import Operation from "antd/lib/transfer/operation";
import { PlusCircleOutlined } from '@ant-design/icons';
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student</Button>
</Form.Item>
</>
)}
</Form.List>
</form>
</div>
);
}
export default App;
I don't know what went wrong, only see the warning in the first pict.
CodePudding user response:
You're missing Form.Provider
. You need it in order to use Form
import { FormProvider } from 'react-hook-form';
After that make sure to wrap your <Form>
tag with a <FormProvider>
tag.
function App() {
return (
<div className="App">
<h2>Dynamic Form Dengan Validasi</h2>
<FormProvider>
<Form>
<Form.Item name={"teacher"} label="Teacher Name">
<Input placeholder="Teacher Name"></Input>
</Form.Item>
<Form.Item name={"class"} label="Class Name">
<Input placeholder="Class"></Input>
</Form.Item>
<Form.List name={"students"}>
{(fields, {add, remove}) => (
<>
{fields.map((field, index)=>{
return (
<Form.Item name={[field.name,"first"]} label={`${index 1}-Student`}>
<Input placeholder="First Name"></Input>
</Form.Item>
);
})}
<Form.Item>
<Button icon={<PlusCircleOutlined />} type="dashed" block onClick={() => { add();}}>
Add A Student
</Button>
</Form.Item>
</>
)}
</Form.List>
</Form>
</FormProvider>
</div>
);
}
CodePudding user response:
- when you create a form, it prefers to use with onSubmited and
- you need to use useState to save the inputs
- pls upload the code to codesandbox that will be much easier to help:)