How to capture entire input object in React - javascript

I am working on my React project. I have a question on how to capture entire form object when user submit all the inputs information. For example, in Node.js Mongoose, req.body returns entire object.
How can I get the entire form submit object in react? Thanks.
This is my form code in React:
return (
<div>
<ol>
{listItems}
<div style={styles.input}>
<form>
<input onChange={this.updateUsername.bind(this)} id='image' className='form-control' type='text' placeholder='image'/><br />
<input onChange={this.updateUsername.bind(this)} className='form-control' type='text' placeholder='Username'/><br />
<input className='form-control' type='text' placeholder='Age'/><br />
<input className='form-control' type='text' placeholder='Gender'/><br />
<input className='form-control' type='text' placeholder='Activity'/><br />
<input className='form-control' type='text' placeholder='Location'/><br />
<input className='form-control' type='text' placeholder='ZipCode'/><br />
<button onClick={this.submitComment.bind(this)} className='btn btn-primary'>Submit Activity</button>
</form>
</div>
</ol>
</div>
)

function wr(e,v){e.innerHTML=v;}
wr(document.body,"
<div>
<ol>
{listItems}
<div style={styles.input}>
<form>
<input onChange={this.updateUsername.bind(this)} id='image' className='form-control' type='text' placeholder='image'/><br />
<input onChange={this.updateUsername.bind(this)} className='form-control' type='text' placeholder='Username'/><br />
<input className='form-control' type='text' placeholder='Age'/><br />
<input className='form-control' type='text' placeholder='Gender'/><br />
<input className='form-control' type='text' placeholder='Activity'/><br />
<input className='form-control' type='text' placeholder='Location'/><br />
<input className='form-control' type='text' placeholder='ZipCode'/><br />
<button onClick={this.submitComment.bind(this)} className='btn btn-primary'>Submit Activity</button>
</form>
</div>
</ol>
</div>
");

I suggest referring to this question when working with forms in React.
However, to your actual question, I don't think there is a way to receive the entire object from the form. What you should do, is set the state of each input field's value, and use the state in the submit function.

We can use onSubmit to get the "form submit object". .target of the event references to the form, and input elements can be found in form.elements.
function submitData(form) {
return [].slice.call(form.elements).reduce((data, {name, value}) => {
if (name) data[name] = value
return data
}, {})
}
class App extends React.Component {
handleSubmit(event) {
event.preventDefault()
this.setState(submitData(event.target))
}
render() {
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<input name="username" placeholder="Username" />
<input name="age" placeholder="Age" />
<button type="submit">Submit</button>
<pre>{JSON.stringify(this.state || {}, null, 2)}</pre>
</form>
)}
}
ReactDOM.render(<App />, document.querySelector('#app-root'))
<div id="app-root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Related

how to clear form after submit in next js?

here I have a contact form and i want all the values of form should be empty after submitting the form.
I have written following code.but this is not working after submitting the values of form remains same.
what is the problem here and how to solve it.
export default function contact() {
const[name,setName]=useState("")
const[phone,setPhone]=useState("")
const[email,setEmail]=useState("")
const[query,setQuery]=useState("")
const [submitted, setSubmitted] = useState(false)
const handleSubmit=(e)=>{
e.preventDefault()
console.log(e);
let data = {
name,
email,
phone,
query
}
console.log(data);
axios.post('http://127.0.0.1:8000/api/create/',data).then((res)=>{
console.log(res);
setSubmitted(true)
setName('')
setPhone('')
setEmail('')
setQuery('')
})
}
return (
<>
<div>
<h1>Contact Page</h1>
</div>
<div >
<form action="contact" method="post">
<input name="name" onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / ><br />
<input name="phone" onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" /><br />
<input name="email" onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / ><br />
<textarea name="text" onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea><br />
<button onClick={(e)=>{handleSubmit(e)}} value="Send" >Submit </button>
</form>
</div>
</>
)
}
Currently you are missing value prop in your inputs so your inputs are uncontrolled components that's why you are not able to clear them after form submit.
Try to add value prop like below:-
<input name="name" value={name} onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / ><br />
<input name="phone" value={phone} onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" /><br />
<input name="email" value={email} onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / ><br />
<textarea name="text" value={query} onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea><br />
Add value prop your inputs then your form shall be cleared after submit:
<form>
<input name="name" value={name} onChange={(e)=>{setName(e.target.value)}} placeholder="Name" / ><br />
<input name="phone" value={phone} onChange={(e)=>{setPhone(e.target.value)}} placeholder="Phone" /><br />
<input name="email" value={email} onChange={(e)=>{setEmail(e.target.value)}} type="email" placeholder="E-mail" / ><br />
<textarea name="text" value={query} onChange={(e)=>{setQuery(e.target.value)}} placeholder="How can we help you?" ></textarea><br />
</form>
First, make sure that your api-call ends successfully, according your code, you clean form only when request passed successfully :)
I think a better way to do this is to rest the form using the .reset() method.
Like this:
document.getElementById("postCodeForm").reset();

button type='submit' with onClick

Which function, submit or onClick will run first? Or will they run simultaneously?
In my program onClick function runs first and then onSubmit. But why and is it always like that?
<Form onSubmit={handleSubmit}>
<Form.Field>
<label>Enter new password:</label>
<input
type="text"
name= 'newPassword'
onChange={handleOnChange}
placeholder='New Password'
required
/>
</Form.Field>
<Button type='submit' onClick={handleClick}>Submit</Button>
</Form>
If you are using formik you can pass handleSubmit to your button onClick and use your code and logics in the callback onSubmit
<Form onSubmit={(values) => yourHandleSubmitMethod(values)}>
<Form.Field>
<label>Enter new password:</label>
<input
type="text"
name= 'newPassword'
onChange={handleOnChange}
placeholder='New Password'
required
/>
</Form.Field>
<Button type='submit' onClick={handleSubmit}>Submit</Button>
</Form>

Form elements and associated labels

How to make associated labels for form elements in below code?
render() {
return (
<section className="col">
<div className="input-group">
<input type="text"
id="search-input"
ref="searchInput"
className="form-control"
placeholder="Filter location..."
onChange={this.handleChange} />
<span className="input-group-addon">Filter</span>
</div>
</section>
)
}
Use below.
<section className="col">
<div className="input-group">
<label for="search-input">Filter</label>
<input type="text"
id="search-input"
ref="searchInput"
className="form-control"
placeholder="Filter location..."
onChange={this.handleChange} />
</div>
</section>
Create label and give input elements id to label's for attribute

Reactjs default Form validation with event.preventDefault()

I do not want to submit form clicking on submit. So i am using :
onSubmit (e) {
e.preventDefault();
console.log(this.state);
}
<form className="loginform">
<h1 className="logo"><img src={images.Logo} /></h1>
<input
className="login"
placeholder="Username"
type="text"
required="true"
onBlur={(e) => { this.userName(e); }}
/>
<input className="login" placeholder="Password" type="password" required="true" />
<input
className="submit"
onClick={(e) => { this.onSubmit(e); }}
type="submit"
value="Submit"
/>
</form>
Doing so form validation is not working. I want to use default form validation with preventDefault.
You should use onsubmit form event:
<form className="loginform" onSubmit={this.onSubmit.bind(this)}>
<h1 className="logo"><img src={images.Logo} /></h1>
<input
className="login"
placeholder="Username"
type="text"
required="true"
onBlur={(e) => { this.userName(e); }}
/>
<input className="login" placeholder="Password" type="password" required="true" />
<input
className="submit"
type="submit"
value="Submit"
/>
</form>
In general you should avoid handling form submission via button onclick events, additional benefit of onsubmit is that it will also be fired on ENTER key submission.

Redux Form submit values without hitting submit

I am pretty sure that there is a way to do this with onChange, but in the example: http://redux-form.com/6.0.0-alpha.4/examples/simple/ here provided by redux form when you click the drop down and hit a value it automatically submits the value without having to hit submit.
I copied the exact code and everything works except for the fact that I have to choose all the values I want then hit submit. How do we make it to where we can just start typing in a field or select a value and it automatically get submitted as they have.
I will put the code below incase you do not want to visit the link.
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const { DOM: { input, select, textarea } } = React
const SimpleForm = (props) => {
const { handleSubmit, pristine, reset, submitting } = props
return (
<form onSubmit={handleSubmit}>
<div>
<label>First Name</label>
<div>
<Field name="firstName" component={input} type="text" placeholder="First Name"/>
</div>
</div>
<div>
<label>Last Name</label>
<div>
<Field name="lastName" component={input} type="text" placeholder="Last Name"/>
</div>
</div>
<div>
<label>Email</label>
<div>
<Field name="email" component={input} type="email" placeholder="Email"/>
</div>
</div>
<div>
<label>Sex</label>
<div>
<label><Field name="sex" component={input} type="radio" value="male"/> Male</label>
<label><Field name="sex" component={input} type="radio" value="female"/> Female</label>
</div>
</div>
<div>
<label>Favorite Color</label>
<div>
<Field name="favoriteColor" component={select}>
<option></option>
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
<div>
<label htmlFor="employed">Employed</label>
<div>
<Field name="employed" id="employed" component={input} type="checkbox"/>
</div>
</div>
<div>
<label>Notes</label>
<div>
<Field name="notes" component={textarea}/>
</div>
</div>
<div>
<button type="submit" disabled={pristine || submitting}>Submit</button>
<button type="button" disabled={pristine || submitting} onClick={reset}>Clear Values</button>
</div>
</form>
)
}
export default reduxForm({
form: 'simple' // a unique identifier for this form
})(SimpleForm)

Categories

Resources