Disable link on ant design form submit - javascript

While trying to create a checkout page for my e-commerce site i ran into this issue.
Using ant designs form component, how do you disable a link (continue to delivery) if all the required forms are not filled? Something like this, were the link should be disabled if the phone number field is not filled.
<Form.Item
name={inputField.phoneNo}
rules={[
{ required: true, message: "Please input your Phone Number!" },
]}
>
<Input placeholder="Phone Number" />
</Form.Item>
<div>
<Link to="/Cart">{"<"} return to cart</Link>
<Form.Item>
<Link
to="/Delivery"
style={{ float: "right" }}
>
<Button htmlType="submit">
Continue to Delivery
</Button>
</Link>
</Form.Item>
</div>

as per Ant design documents you can disable button like following
const [form] = Form.useForm();
const [, forceUpdate] = useState();
useEffect(() => {
forceUpdate({});
}, []);
<Form.Item shouldUpdate={true}>
{() => (
<Button
type="primary"
htmlType="submit"
disabled={!form.isFieldsTouched(false) ||
form.getFieldsError().filter(({ errors }) => errors.length).length}>
Log in</Button>)}
</Form.Item>

you can write custom logic for it something like:
<Button
disabled={
!form.isFieldsTouched(true) ||
form.getFieldsError().filter(({ errors }) => errors.length).length
}
htmlType="submit"
>
Continue to Delivery
</Button>

Related

React input value doesnt work with states

I have weird error. When i try change my input value with a state its not working but if i write my state some void place so its start changing value. Why its being like that ? My codes :
<Form
className="mt-4"
layout="vertical"
requiredMark="hidden"
name="basic"
form={form}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
name="Name"
label="Başlık"
style={{ width: 400 }}
rules={[{ required: true, message: "Lütfen Başlık Giriniz!" }]}
>
<Input
id="IDTitle"
placeholder="Başlık"
onChange={handleInputChange}
/>
</Form.Item>
<Form.Item name="Url" label="URL" style={{ width: 400 }}>
{titleData} // if i write it its working. But if i delete that row its not shows or update value.
<Input placeholder="Url" disabled value={titleData}></Input>
</Form.Item>
<Button
type="primary"
className="submitButton float-right"
htmlType="submit"
>
Submit
</Button>
</Form.Item>
</Form>
const handleInputChange = (e) => {
const data = e.target.value;
console.log(data);
setTitleData(toEnglishChar(data));
};
How can i solve it ? Thanks for all replies! I dont know why its happening like that but i tried everything i can do. I tried change antd input with default input too but it didnt work too. Thanks for all replies !!
Change onChange event like the following:
<Input
id="IDTitle"
placeholder="Başlık"
onChange={e => handleInputChange(e)}
/>

How to hide validation error in React Js upon updating the input field?

I am new to ReactJs and I have a form validated with react-hook-form. Whenever I submit the form, I get the errors displayed which is fine but upon updating the input fields, the error stays. I want the errors to be hidden after change in the input field.
I know it should be done with hooks but since I am new to React, I cannot code my logic.
Here is my code.
export default function SimpleCard() {
const classes = useStyles();
const { register, handleSubmit, errors, reset } = useForm();
const onSubmit = (data, event) => {
event.preventDefault();
console.log(JSON.stringify(data));
reset();
}
return (
<div className={classes.card}>
<Card className={classes.cardBorder} elevation={12}>
<CardContent>
<Typography className={classes.title}>
Log in
<br/>
<span className={classes.subtitle}>(Employee Only)</span>
</Typography>
<hr/>
</CardContent>
<form onSubmit={handleSubmit(onSubmit)} className={classes.root}>
<TextField
size="normal"
placeholder="Enter Your E-mail Address"
label="Email Address"
variant="outlined"
fullWidth
name="email"
inputRef={register({
required: "E-mail Address is required.",
})}
error={Boolean(errors.email)}
helperText={errors.email?.message}
/>
<TextField
size="normal"
placeholder="Enter Your Password"
label="Password"
variant="outlined"
type="Password"
fullWidth
name="password"
inputRef={register({
required: "Password is required.",
})}
error={Boolean(errors.password)}
helperText={errors.password?.message}
/>
<div className={classes.dokmaBG}>
<Button type="submit" variant="contained" size='large' className={classes.dokma}>
<b>Login</b>
</Button>
</div>
</form>
</Card>
</div>
);
}
Can someone guide me on how to use hooks to hide the error messages once the input field is updated?
OnChange, you can update state error object.
const [error, setError] = useState({})
handleChange = (e) => {
let e = {...error}
setError(e)
}

form.validateFields() doesnt work when we have custom antd form component

Considering the following example, this is stopping us to create custom components inside forms using antd4 version.
const handleFormSubmit = () => {
form
.validateFields()
.then((values: any) => {
console.log('success values => ', JSON.stringify(values));
successCallback(values);
})
.catch((errorInfo: any) => {
console.log('failureCallback values => ', JSON.stringify(errorInfo));
failureCallback(errorInfo);
});
};
<Form
form={form}
layout="vertical"
name="normal_login"
className="login-form"
initialValues={store.formData.initialValues}
>
<Form.Item>
<Input placeholder="Name" />
</Form.Item>
<Button type="primary" htmlType="submit" onClick={handleFormSubmit}>
Create
</Button>
</Form>
This works absolutely fine, whereas if the component is custom, then it doesn't work. Example:
function CustomInput(props){
return (
<Form.Item>
<Input placeholder={props.name} />
</Form.Item>
)
}
<Form
form={form}
layout="vertical"
name="normal_login"
className="login-form"
initialValues={store.formData.initialValues}
>
<CustomInput name="Name" />
Will display the field and also validates on change event. HandleFormSubmit is called, but it's not triggering success or failure block.
<Button type="primary" htmlType="submit" onClick={handleFormSubmit}>
Create
</Button>
</Form>
What's wrong here?
Try this instead of your Custom JSX
function CustomInput(props){
return (
<Form.Item name={props.name}> # Update this line only and remove this comment #
<Input placeholder={props.name} />
</Form.Item>
)
}
<Form
form={form}
layout="vertical"
name="normal_login"
className="login-form"
initialValues={store.formData.initialValues}
>
<CustomInput name="Name" />
<Button type="primary" htmlType="submit" onClick={handleFormSubmit}>
Create
</Button>
</Form>
NOTE: In Antd if your using Form.Item then you have to set name there
not on input fields. Form.Item assign its value to its Input.
I hope your doubt is solved comment for more views. I also tired of antd and wasted many days to understand this.

validation keeps working from deleted rows in a dynamic form in Antd

I'm following the docs of Antd and tried to use this piece of code from here antd dynamic form item:
import { Form, Input, Button, Space } from 'antd';
import { MinusCircleOutlined, PlusOutlined } from '#ant-design/icons';
const Demo = () => {
const onFinish = values => {
console.log('Received values of form:', values);
};
return (
<Form name="dynamic_form_nest_item" onFinish={onFinish} autoComplete="off">
<Form.List name="users">
{(fields, { add, remove }) => (
<>
{fields.map(field => (
<Space key={field.key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
<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
{...field}
name={[field.name, 'last']}
fieldKey={[field.fieldKey, 'last']}
rules={[{ required: true, message: 'Missing last name' }]}
>
<Input placeholder="Last Name" />
</Form.Item>
<MinusCircleOutlined onClick={() => remove(field.name)} />
</Space>
))}
<Form.Item>
<Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
Add field
</Button>
</Form.Item>
</>
)}
</Form.List>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
But I have this error, when I add some rows, then delete some of them and finally submit, the validator keeps working even after I had deleted those rows.
Here is a demo that replicates my error.
https://codesandbox.io/s/quizzical-ride-m1pe6?file=/src/App.js
This is a bug from antd.
An issue was opened about that on their github.
https://github.com/ant-design/ant-design/issues/27576
And the associate PR :
https://github.com/react-component/field-form/pull/213
A fix has been merged last week. Normally, the next release will include the fix.

Why the autofocus isn't working in ReactJS with antd?

I'm having trouble with the autoFocus, I searched a lot, but none solutions that I found worked for me, I'm using a Drawer with a form inside, that form has some Form.Item with Input, and when I open the drawer, I want to focus on form.item, anybody can help me?
Here is my code:
<Drawer>
<Form layout="vertical" ref={this.formRef} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed}>
<Row gutter={16}>
<Col span={24}>
<Form.Item
name="description"
label="Description"
rules={[
{
required: true,
message: 'Please enter a description.',
},
]}
>
<Input.TextArea autoFocus rows={10} placeholder="Please enter a description." />
</Form.Item>
</Col>
</Row>
<Row style={{ bottom: '0', position: 'absolute', right: '38px' }}>
<Form.Item>
<Button
onClick={this.onClose}
style={{ marginRight: 8 }}
>
Cancel
</Button>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Row>
</Form>
</Drawer>
According to the docs, autoFocus is not supported prop (like it is on <input /> element). Haven't used this ui lib before, so can't say if setting focus manually by using ref would work.
UPDATE:
Just have played a bit and it looks like that focus can be set manually:
demo
code
Another update:
demo with drawer
code
const inputTagRef = useRef(null);
useEffect(() => {
if (inputTagRef.current) {
inputTagRef.current.focus();
}
}, [inputTagRef.current]);
<Input
ref={inputTagRef}
/>
This will add autoFocus to you input field using antd ui lib.

Categories

Resources