score:5
the answer is complex for all your questions.
first of all, it depends on the task: if you just want to send asynchonous request to server on form submit, you don't need to use component
state. here is a link to the relevant section of the documentation. and use refs to access inputs data.
class formcomponent extends react.component {
constructor(props) {
super(props);
this.onsubmit = this.onsubmit.bind(this);
}
onsubmit(e) {
e.preventdefault();
// send your ajax query via jquery or axios (i prefer axios)
axios.get('your_url', {
params: {
action: this.actioninput.value,
email: this.emailinput.value,
password: this.passwordinput.value,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
render() {
return (
<form onsubmit={this.onsubmit}>
<input type="hidden" name="action" value="login"
ref={(input) => { this.actioninput = input }} />
<input type="email" name="email_user" placeholder="email"
ref={(input) => { this.emailinput = input }}/>
<input type="password" name="password_user" placeholder="mot de passe"
ref={(input) => { this.passwordinput = input }}/>
<button type="submit">login</button>
</form>
);
}
}
score:0
answering your questions:
since you know how to use component's state you may set the value as :
<input type='text' value={this.state.foo} />
or even via props passing<input type='hidden' value={this.props.foo} />
you don't need to serialise anything at all. use your component's local state or even a state container like redux or flux in order to pick the appropriate data. take a look at this fairly simple example:
var superform = react.createclass({ getinitialstate() { return { name: 'foo', email: 'baz@example.com' }; }, submit(e){ e.preventdefault(); console.log("send via ajax", this.state) }, change(e,key){ const newstate = {}; newstate[key] = e.currenttarget.value; this.setstate(newstate) }, render: function() { return ( <div> <label>name</label> <input onchange={(e) => this.change(e,'name')} type="text" value={this.state.name} /> <label>email</label> <input onchange={(e) => this.change(e,'email')} type="text" value={this.state.email} /> <button onclick={this.submit}>submit</button> </div> ); }});
ajax is a set of web development techniques while axios is a javascript framework. you may use jquery, axios or even vanilla javascript.
score:1
all data can be stored on react's state, but if you still need to have inputs on your form you can do something like this:
const handlesubmit = e => {
e.preventdefault();
const inputs = object.values(e.target)
.filter(c => typeof c.tagname === 'string' && c.tagname.tolowercase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
setformvals({ ...formvals, ...inputs });
}
see the demo below:
const demo = () => {
const [formvalues] = react.usestate({});
const handlesubmit = e => {
e.preventdefault();
const inputs = object.values(e.target)
.filter(c => typeof c.tagname === 'string' && c.tagname.tolowercase() === 'input')
.reduce((acc, curr) => ({ ...acc, [curr.name]: curr.value }), {});
console.log(inputs);
}
return (
<form onsubmit={handlesubmit}>
<input name="name" placeholder="name" value={formvalues.name} />
<input name="email" placeholder="email" value={formvalues.email} />
<input name="hiddeninput" value="hiddenvalue" type="hidden" />
<button type="submit">submit</button>
</form>
);
}
reactdom.render(<demo />, document.getelementbyid('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
if you know what the inputs that you need you can do something like this:
const demo = () => {
const formref = react.useref(null);
const [formvalues, setformvalues] = react.usestate({});
const handlechange = e => {
setformvalues({
...formvalues,
[e.target.name]: e.target.value,
});
}
const handlesubmit = e => {
e.preventdefault();
setformvalues({ ...formvalues, hiddeninput: formref.current.hiddeninput.value });
}
return (
<form onsubmit={handlesubmit} ref={formref}>
<input name="name" placeholder="name" value={formvalues.name} onchange={handlechange} />
<input name="email" placeholder="email" value={formvalues.email} onchange={handlechange} />
<input name="hiddeninput" value="hiddenvalue" type="hidden" />
<button type="submit">submit</button>
<pre>{json.stringify(formvalues, null, 2)}</pre>
</form>
);
}
reactdom.render(<demo />, document.getelementbyid('demo'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="demo"></div>
Source: stackoverflow.com
Related Query
- How to send input hidden in React JS?
- React warning: contains an input of type hidden with value and default value - how to fix?
- How to send info from a reusable input to the other components in React
- How to send the Input Fields in React Function component to a function
- React - How can I get the values from my multiple input and send them to my input?
- How to create a form with text and file input in react and send form data to server using Nodejs?
- How to send a form input data containing both image and text from React front-end to Express backend using Multer
- How can transfer values collected from a modal to a hidden form input outside the modal React
- How to align text input correctly in react native?
- How to send request on click React Hooks way?
- How to allow input type=file to select the same file in react component
- How can I get input radio elements to horizontally align in react [material-ui]?
- how react programmatically focus input
- How do I store JWT and send them with every request using react
- How can I test a change handler for a file-type input in React using Jest/Enzyme?
- How to send params in useHistory of React Router Dom?
- How to keep cursor position in a react input element
- How to change outline color of Material UI React input component?
- Send cursor to the end of input value in React
- How do I listen to keyboard input in React Native
- How to clear input values of dynamic form in react
- how to hold file input value in react
- How to create a controlled input with empty default in React 15
- how to send email directly in React Native App
- How do I reset the defaultValue for a React input
- How to get form data from input fields in React
- How to limit the text filed length with input type number in React JS and prevent entry of E,e, -, + etc
- React Typescript how send props and use it in child component
- How can we send OAuth2.0 with axios in React js
- How to make React input onChange set state only after onChange stops firing for set time?
More Query from same tag
- ReactJS show modal popup form on specified keystroke
- How to trigger a function of sibling component in React?
- React - child elements not rerendering
- Using package.json script to run another package.json script
- React: How to create table from the following json
- How to receive json return message in saga try catch when it fails?
- Recursively enter nested object into tree view component inside return statement of a React functional component
- How to run 2 instances of ReactI18Next on the same app?
- Is it possible to place Cypress tests in existing React file architecture
- Set new color for material-ui theme
- How to do a custom interactive "map" with an image with React?
- Handle react event and legacy library event together
- Displaying images with img tag in React.js
- mapStateToProps returning undefined state from reducer
- Revert changes in redux store
- Using OOP in react js
- Destructuring mapStateToProps in JS
- How to add global style in sharepoint framework(SPFx)?
- How to conditionally disable the submit button with react-hook-form?
- Stripe custom payment flow isn't showing checkout form in React.js
- React |How to Update parent state when multiple children sending event to parent at same time
- React Push One State Array into Another
- REACT_APP_KEY from .env in root not being accessed
- How to truncate a overflowed text in a react element with middle ellipsis?
- How to create a sticky navbar on react (inside a div)
- Nextjs fatal production only error after adding new package
- how to get data from following response in reactjs
- Slide Up Transition of React Component
- How to use Real time chart in react?
- How to match a template string in switch statement with js?