Home > Net >  Reset form input field after clicking submit on react js using useState
Reset form input field after clicking submit on react js using useState

Time:10-27

I have a sign in form working just fine and I want to set the input fields blank after clicking submit. I searched for similar questions, but most people were using react hook and other stuff that I am not using, so I don't know how to adapt these solutions to mine. Here is my code:

import React, { useState } from 'react';
import { 
    FormWrap,
    Container, 
    Icon, 
    FormContent, 
    Form,
    FormH1,
    FormLabel, 
    FormInput,
    Text, 
    FormButton, 
    TextLeft,
    Heading,
    Subtitle,
    TextWrapper,
    LogoPage,
    ModalWrapper,
    FormMiniLabel, Wrapper, FormInputTerms, TermLink, FormMiniLabelWarning} 
from './SignInElements'
import Axios from 'axios'
import { Modal} from '../Modal/Modal';




const SignIn = ({}) => {
    const[name, setname] = useState("");
    const[cpf, setcpf] = useState("");
    const[tel, settel] = useState("");
    const[email, setemail] = useState("");
    const[terms, setterms] = useState("");

    const register = () => {
        Axios.post('http://localhost:3001/register/',  {
            name: name,
            cpf: cpf,
            tel: tel,
            email: email,
        }).then((response) => {console.log(response)});
        console.log(name);
        console.log(cpf);
        console.log(tel);
        console.log(email);
        console.log(terms);
        
    };
    
    const [showModal, setShowModal] = useState(false);

    const OpenModal = () => {
        setShowModal(prev => !prev);
    };


    function AllFunc() {
        register();
        OpenModal();
    }


    function SubmitButton(){
        if (name && cpf && tel && email && terms){
          return <FormButton type="submit" onClick={AllFunc}>Cadastrar</FormButton>
        } else {

          return (
          <FormButton type="submit">Cadastrar</FormButton>)
        };
      };

    return (
        <>
            <Container>
                <FormWrap>
                    <FormContent>
                        <TextLeft  action="#">
                            <Icon to="/"> <LogoPage src={require('../../images/Brand.svg').default} /> </Icon>
                            <TextWrapper>
                                <Heading>Bora parcelar com a Wowpen? </Heading>
                                <Subtitle>Cadastre-se completando o formulário e participe do nosso grupo seleto de beta testers. Tenha acesso antecipado a funcionalidade de parcelamento e interaja diretamente com o nosso time de desenvolvimento.</Subtitle>
                            </TextWrapper>
                        </TextLeft>
                        <Form action="#">
                            <FormLabel htmlFor="for">Como podemos te chamar?</FormLabel>
                            <FormInput placeholder="Nome Sobrenome" type="text" required onChange={(e) => setname(e.target.value) }/>
                            <FormLabel htmlFor="for">Compartilha seu CPF?</FormLabel>
                            <FormMiniLabel>É importante para verificar sua identidade.</FormMiniLabel>
                            <FormInput placeholder="000.000.000-00" type="text" required  onChange={(e) => setcpf(e.target.value) }/>
                            <FormLabel htmlFor="for">Qual seu número de Whatsapp?</FormLabel>
                            <FormMiniLabel>Esse é nosso principal meio de comuniação.</FormMiniLabel>
                            <FormInput placeholder="(DDD) 90000-0000" type="text" required onChange={(e) => settel(e.target.value) } />
                            <FormLabel htmlFor="for">E seu e-mail?</FormLabel>
                            <FormMiniLabel>Prometemos não enviar spam ;)</FormMiniLabel>
                            <FormInput placeholder="[email protected]" type="email" required onChange={(e) => setemail(e.target.value) } />
                            <Wrapper>
                            <FormInputTerms type="checkbox" required onChange={(e) => setterms(e.target.value) } />
                            <FormMiniLabel>Li e concordo com os <TermLink>Termos e a Política de Privacidade</TermLink> da Wowpen. </FormMiniLabel>
                            </Wrapper>
                            <SubmitButton/>
                        </Form>
                        <Modal setShowModal={setShowModal} showModal={showModal}/>
                    </FormContent>
                </FormWrap>
            </Container>
        </>
    )
}

export default SignIn

Basically, there is the SubmitButton function that, when all fields are filled, triggers the functions that send the data for a MySQL database (register) and open a modal (openModal). I have tried to add a function called reset like:

function reset () {
   setname("");
   settel("");
}

To be called on the submit button click, but it's not working to make the fields blank.

The Form component is below (i am using styled-components):

export const Form = styled.form`
    background: #fff;
    background-image: url(${img});
    background-size: 100% 100%;
    background-position:center;
    background-repeat:no-repeat;
    max-width: 100%;
    height: 100%;
    width: 100%;
    display: grid;
    grid-area: col2;
    padding: 80px 147px;
    align-content: center;

    @media screen and (max-width: 480px) {
        padding: 32px 32px;
    }

    @media screen and (max-width: 700px) {
        padding: 80px 60px;
        height: 1200px;
        width: 100%;
        justify-content: center;
        background-size: cover;
        
    }
    

    @media only screen and (min-width: 1500px) and (max-width: 1501px) {
        height: 1200px;
        width: 100%;
        padding: 0;
        justify-content: center;
    }
`;

And the Form Input component (also with styled-components):

export const FormInput = styled.input`
    padding: 16px 16px;
    /*margin-bottom:  32px;*/
    border: none;
    height: 56px;
    border-radius: 4px;
    font-size: 18px;
    background-color: #F6F6F6;
    margin-bottom: 24px;
`;

Does anyone know how can I set the input fields blank after submitting?

CodePudding user response:

I have changed all inputs to a controlled input, so whenever your state changes it automatically reflect in your input box also Added value to all FromInputs <FormInput value={name} ...

SO after changing to controlled elements you can now clear text box value by clearing the state

import React, { useState } from 'react';
import { 
    FormWrap,
    Container, 
    Icon, 
    FormContent, 
    Form,
    FormH1,
    FormLabel, 
    FormInput,
    Text, 
    FormButton, 
    TextLeft,
    Heading,
    Subtitle,
    TextWrapper,
    LogoPage,
    ModalWrapper,
    FormMiniLabel, Wrapper, FormInputTerms, TermLink, FormMiniLabelWarning} 
from './SignInElements'
import Axios from 'axios'
import { Modal} from '../Modal/Modal';




const SignIn = ({}) => {
    const[name, setname] = useState("");
    const[cpf, setcpf] = useState("");
    const[tel, settel] = useState("");
    const[email, setemail] = useState("");
    const[terms, setterms] = useState("");

    const register = () => {
        Axios.post('http://localhost:3001/register/',  {
            name: name,
            cpf: cpf,
            tel: tel,
            email: email,
        }).then((response) => {
           console.log(response)
            setname("");
            settel("");
            setcpf("");
            setemail("");
            setterms(false)
        });
        
    };
    
    const [showModal, setShowModal] = useState(false);

    const OpenModal = () => {
        setShowModal(prev => !prev);
    };


    function AllFunc() {
        register();
        OpenModal();
    }


    function SubmitButton(){
        if (name && cpf && tel && email && terms){
          return <FormButton type="submit" onClick={AllFunc}>Cadastrar</FormButton>
        } else {

          return (
          <FormButton type="submit">Cadastrar</FormButton>)
        };
      };

    return (
        <>
            <Container>
                <FormWrap>
                    <FormContent>
                        <TextLeft  action="#">
                            <Icon to="/"> <LogoPage src={require('../../images/Brand.svg').default} /> </Icon>
                            <TextWrapper>
                                <Heading>Bora parcelar com a Wowpen? </Heading>
                                <Subtitle>Cadastre-se completando o formulário e participe do nosso grupo seleto de beta testers. Tenha acesso antecipado a funcionalidade de parcelamento e interaja diretamente com o nosso time de desenvolvimento.</Subtitle>
                            </TextWrapper>
                        </TextLeft>
                        <Form action="#">
                            <FormLabel htmlFor="for">Como podemos te chamar?</FormLabel>
                            <FormInput value={name} placeholder="Nome Sobrenome" type="text" required onChange={(e) => setname(e.target.value) }/>
                            <FormLabel htmlFor="for">Compartilha seu CPF?</FormLabel>
                            <FormMiniLabel>É importante para verificar sua identidade.</FormMiniLabel>
                            <FormInput value={cpf} placeholder="000.000.000-00" type="text" required  onChange={(e) => setcpf(e.target.value) }/>
                            <FormLabel htmlFor="for">Qual seu número de Whatsapp?</FormLabel>
                            <FormMiniLabel>Esse é nosso principal meio de comuniação.</FormMiniLabel>
                            <FormInput value={tel} placeholder="(DDD) 90000-0000" type="text" required onChange={(e) => settel(e.target.value) } />
                            <FormLabel htmlFor="for">E seu e-mail?</FormLabel>
                            <FormMiniLabel>Prometemos não enviar spam ;)</FormMiniLabel>
                            <FormInput value={email} placeholder="[email protected]" type="email" required onChange={(e) => setemail(e.target.value) } />
                            <Wrapper>
                            <FormInputTerms checked={terms} type="checkbox" required onChange={(e) => setterms(e.target.checked) } />
                            <FormMiniLabel>Li e concordo com os <TermLink>Termos e a Política de Privacidade</TermLink> da Wowpen. </FormMiniLabel>
                            </Wrapper>
                            <SubmitButton/>
                        </Form>
                        <Modal setShowModal={setShowModal} showModal={showModal}/>
                    </FormContent>
                </FormWrap>
            </Container>
        </>
    )
}

export default SignIn

Other than this method I suggest to use a single state object to handle all the values, like const [data, setData] = useState({}) by using this method you can handle all value in one object and you could quickly clear it

CodePudding user response:

you need to add onSubmit to the Form tag

 <Form action="#" onSubmit={onSubmit}>

then create a function that should perform after clicking the Submit button

const onSubmit = e => {
   e.preventDefault()

   // do something
   
   setname("");
   settel("");
}
  • Related