简体   繁体   中英

How to get form data as a object in reactjs

I'm trying to create a google form with react, I have been creating all the questions as a components

if (props.type == "text") {
    return (
        <div className="box">
            <h3 className="">{props.qustion}</h3>
            <input className="short-text" placeholder="Your answer" id={"text"+props.id} name={"q"+props.id} type="text" onChange={updateField}/>
        </div>
    )
}

else if (props.type == "choice") {
    return (
        <div className="box">
            <h3 className="">{props.qustion}{props.requre? <label className="requir">*</label>:""}</h3>
            {props.answer.map(ans=>(
            <div key={ans}>
                <input className="radio" type="radio" id={ans} name={"radio"+props.id} value={ans} required={props.requre} onChange={updateField}/>
                <label htmlFor={ans}>{ans}</label>
            </div>
            ))

            }
        </div>
    )

and I have been creating a form on the app file and put the components inside him,

  return (
<div className="App">
    <FormTitle/>
    <form>
    {  
     error? <h1>the sorce not found</h1>:data.map((item) =>(<Qustion qustion={item.question} type={item.type} requre={item.requre} id={item.id} answer={item.answares} key={item.id} />))
    }
    <div className="submit-right">
      <input className="submit-button" type="submit" value="Submit" />
    </div>
    </form>
</div>

);

how to get all the form data as an object to create a post request??

Try this function at start of the file where the form is

  const formSubmit = (event) => {
    event.preventDefault();
    var data = new FormData(event.target);
    let formObject = Object.fromEntries(data.entries());
    console.log(formObject);
  }

and in the form use this onSubmit={formSubmit}

    <form onSubmit={formSubmit}>
       <any element or components>
    </form>

entries is not a function you can just reach it

  const formSubmit = (event) => {
    event.preventDefault();
    var data = new FormData(event.target);
    let formObject = Object.fromEntries(data.entries);
    console.log(formObject);
  }

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