Search code examples
node.jsreactjsreact-fullstack

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 ??


Solution

  • 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>