简体   繁体   中英

React-Hook-Form and ReactJS Components Validation

Please note I'm new to ReactJS as a whole(I've only been studying it for like 4 days).

I have 3 JS files.

I'm trying to implement React-Hook-Form into my application.

I've followed as much as I could the sample codes from the main site itself . You can see its attempt in the FormEntry.js section.

Without the ...register() code, my application works as expected. User inputs data, it gets submitted as part of an API call which returns some sample data based on the input.

After adding the ...register() , mainly to test the validation, the validation itself works: I cant submit the form without having an input in my field and an error message displays. However, the validation still fails even if I have input in the field .

Where am I going wrong with this?

These are my relevant JS codes.(may be a bit messy)

Create.js is basically the main page users will see when they enter my site that displays a input form to create an object.

import { useState } from "react";
import FormEntry from '../components/FormEntry';

function CreatePage() {
    /*
    useState
    value1 = the value save
    value2 = the method to call to update value1
    */
    const [responseData, setData] = useState([]);

    function getCreateData(allData){
        console.log("getCreateData allData");
        console.log(allData);
        fetch(<API url>,{
            "method": 'POST',
            "body": JSON.stringify(allData),
            "headers":{
                "Content-Type": 'application/json'
            }
        })
        .then(res => res.json())
        .then(
            (result) => {
                setData(result);
                console.log(result);
            }
        );
    }

    return (
        <div>
            <h2 align="center" >Create Proposal</h2>
            <FormEntry responseInputData={getCreateData} />
        </div>
        
    );
}

export default CreatePage; //allows function to be useable by others

The input the user made will be parsed into the getCreateData function where it will call an API. The allData variable comes from the FormEntry.js component, which forms the bulk of the Create.js page.

import { useRef } from "react";
import FieldEntry from "./FieldEntry";
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import SearchIcon from '@mui/icons-material/Search';
import SaveIcon from '@mui/icons-material/Save';

import { useForm } from "react-hook-form";

function FormEntry(props){
    const clientRef = useRef();
    const propRefNameRef = useRef();
    const { register, formState: { errors }, handleSubmit } = useForm();

    function submitData(event){
        event.preventDefault();

        const client = clientRef.current.value;
        const propRefName = propRefNameRef.current.value;

        const allData = {
            client: client,
            propRefName: propRefName,
        }

        props.responseInputData(allData);

    }

    return(
        <form className="formEntry" onSubmit={handleSubmit(submitData)}>
            <div class="row" >
                <table >
                    <FieldEntry label="Client" type="text" id="input_client" {...register("client", { required: true })} propsRef={clientRef} />
                    {errors.client?.type === 'required' && "Required Fields"}
                    <FieldEntry label="Proposal" type="text" id="input_propRefName" name="propRefName" propsRef={propRefNameRef} />
                </table>
            </div>
            <Button type="submit" variant="contained" align="center" size="small" startIcon={<SearchIcon />}>Search</Button>
        </form>
    )

}

FieldEntry.js is called as a reusable component to populate the fields in the FormEntry.js

function FieldEntry(props){

    return(
        <tr>
            <td><label htmlFor={props.id}>{props.label}</label></td>
            <td><input type={props.type} name={props.name} id={props.id} ref={props.propsRef} /></td>
        </tr>
    )
}
export default FieldEntry;

The return value of register has an onChange property, which RHF uses to update the field. In your example you are not using this prop in your <FieldEntry /> component.

function FieldEntry(props){

    return(
        <tr>
            <td><label htmlFor={props.id}>{props.label}</label></td>
            <td><input type={props.type} name={props.name} onChange={props.onChange} id={props.id} ref={props.propsRef} /></td>
        </tr>
    )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM