Source:  Twitter logo

I am building a web app using Django rest framework on the backend and React on the frontend. I am also using Ant Design to help with styling. I have been following a tutorial on Youtube but I am currently running into some issues when trying to submit a form to create a new article. I have done some trouble shooting and I believe the issue is with the Form's onSubmit function. I tried adding an onClick to the button to ensure that the click is being recognized and that worked as expected which is why I believe the issue is with the onSubmit. Right now, all I am trying to do is print the form elements to the console. I am super novice with developing web applications so any help would be much appreciated.

import React from 'react';
import { Form, Input, Button } from 'antd';


class CustomForm extends React.Component {

    handleFormSubmit = (event, requestType, articleID) => {
        //event.preventDefault();
        const title = event.target.elements.title.value;
        const content = event.target.elements.content.value;

        console.log(title, content);
    }

    render() {
        return (
            <div>
                <Form
                    onSubmit={event =>
                        this.handleFormSubmit(
                            event,
                            this.props.requestType,
                            this.props.articleID
                        )
                    }
                >
                    <Form.Item label="Title">
                        <Input name="title" placeholder="Enter a Title" />
                    </Form.Item>
                    <Form.Item label="Content">
                        <Input name="content" placeholder="Enter the content of the announcement here" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">{this.props.btnText}</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }
};

export default CustomForm;

The issue is onSubmit according to antd document it should be onFinish here and also you need to pass name along with label in <Form.Item>:

Here is the code:

const Demo = () => {
  const onFinish = (values) => {
    console.log("Success:", values);
    //Can directly call props here
  };

  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <Form
      {...layout}
      name="basic"
      initialValues={{
        remember: true
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item label="Title" name="title">
        <Input name="title" placeholder="Enter a Title" />
      </Form.Item>
      <Form.Item label="Content" name="content">
        <Input
          name="content"
          placeholder="Enter the content of the announcement here"
        />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
};

Here is the demo: https://codesandbox.io/s/competent-violet-opwlh?file=/index.js

6 users liked answer #0dislike answer #06
Shubham Verma profile pic
Shubham Verma

In my case, I used a normal <form> with Ants controlled <Input> elements as the form wasn't being submitted nor the inputs controlled.

/**
 * Component's state
 */
interface LoginSignUpState {
    username: string,
    password: string
}

export class LoginSignUpForm extends React.Component<{}, LoginSignUpState> {
    constructor (props) {
        super(props)

        this.state = {
            username: '',
            password: ''
        }
    }


    /**
     * Updates the component state from the user input
     * @param e Change event
     */
    handleInputChange = (e) => {
        this.setState<never>({ [e.target.name]: e.target.value })
    }


    /**
     * Checks that the login form is valid!
     * @returns True if the login form is valid, false otherwise
     */
    loginFormIsValid (): boolean {
        return this.state.username.trim().length > 0 &&
            this.state.password.trim().length > 0
    }

    handleSubmit = (e) => {
        if (!this.loginFormIsValid()) {
            e.preventDefault()
        }
    }

    render () {
        return (
            <form
                method='POST'
                onSubmit={this.handleSubmit}
                action={urlAuthenticate}
            >
                <Input
                    prefix={<UserOutlined className="site-form-item-icon" />}
                    placeholder="Username"
                    className='margin-bottom-2'
                    name='username'
                    value={this.state.username}
                    onChange={this.handleInputChange}
                />

                <Input
                    prefix={<LockOutlined className="site-form-item-icon" />}
                    value={this.state.password}
                    type="password"
                    className='margin-bottom-2'
                    name='password'
                    placeholder="Password"
                    onChange={this.handleInputChange}
                />

                <Button type="primary" htmlType="submit" disabled={!this.loginFormIsValid()}>
                    Log in
                </Button>
            </form>
        )
    }
}

1 users liked answer #1dislike answer #11
Genarito profile pic
Genarito

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).