I have two fields in the form, but i am not able to post the data to the server. I know how to submit single filed but how do i submit multiple field in the form.
below is the code of 2 fields
class Createstudent extends React.Component {
constructor(props) {
super(props);
this.state = {name: '',
age:''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({name: event.target.value});
this.setState({age:event.target.value});
}
handleSubmit(event) {
alert(this.state.name);
axios.post('/create',{values:this.state.name,ages:this.state.age})
.then(function(response){
console.log(response);
})
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={this.handleChange} />
</label>
<label>
Age:
<input type="text" value={this.state.age} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Reason is you are updating both the fields with the same value, on change of any one, update the specific field, it will work, try this:
handleChange(event) {
if(event.target.name == 'name')
this.setState({name: event.target.value});
else
this.setState({age: event.target.value});
}
or
handleChange(event) {
this.setState({[event.target.name]: event.target.value});
}
Add name attr to input field to identify them uniquely, Use this render method:
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" name='name' value={this.state.name} onChange={this.handleChange} />
</label>
<label>
Age:
<input type="text" name='age' value={this.state.age} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
Check the jsfiddle: https://jsfiddle.net/dp0an79f/
I have changed the code like this.And its working.
import React from 'react';
import axios from 'axios';
class Createstudent extends React.Component {
constructor(props) {
super(props);
this.state = {name: '',
age:''
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
alert(this.state.name);
axios.post('/create',{values:this.state.name,ages:this.state.age})
.then(function(response){
console.log(response);
})
}
componentDidMount(){
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
</label>
<label>
Age:
<input type="text" value={this.state.age} onChange={e => this.setState({ age: e.target.value })} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
Related
I am a beginner in React and trying to make a CRUD app. I have this code snipped where useState is being used but when I use the same in a class with render function it gives an error. Can someone explain me why and can convert this code to suit a class with render
export default function App(){
const[userName,setUserName]=useState('');
const[password,setPassword]=useState('');
return(
<div className="CreatePost">
<label>UserName</label>
<input type="text"
onChange={(e)=>{
setUserName(e.target.value);
}}
/>
<label>Password</label>
<input type="text"
onChange={(e)=>{
setPassword(e.target.value);
}}
/>
</div>
);
}
useState() only works in functional component. if you want to modify state in a class based component you have to do it with setState method. Something like this should work
export default class App extends React.Component{
constructor() {
this.state ={ userName : "" , password: "" }
}
render() {
return(
<div className="CreatePost">
<label>UserName</label>
<input type="text"
onChange={(e)=>{
this.setState( {userName : e.target.value} );
}}
/>
<label>Password</label>
<input type="text"
onChange={(e)=>{
this.setState( {password : e.target.value} );
}}
/>
</div>
);
}
}
You cannot use hook inside class component. Convert your existing component into the class based as following:
class App extends React.PureComponent {
state = {
userName: '',
password: '',
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value,
});
}
render () {
const { userName, password } = this.state;
return (
<div className="CreatePost">
<label>UserName</label>
<input type="text" value={userName} onChange={this.handleChange}/>
<label>Password</label>
<input type="text" value={password} onChange={this.handleChange}/>
</div>
)
}
}
This question already has answers here:
Handle change event of all input fields without using refs
(2 answers)
Closed 2 years ago.
I have several inputs ,Each of the inputs has its own value .How can I have a function for (onChange) all of them ?
For example
handleChange1(event) {
this.setState({value1: event.target.value});
}
handleChange2(event) {
this.setState({value2: event.target.value});
}
}
handleChange3(event) {
this.setState({value3: event.target.value});
}
<input type="text" value={this.state.value1} onChange={this.handleChange1} />
<input type="text" value={this.state.value2} onChange={this.handleChange2} />
<input type="text" value={this.state.value3} onChange={this.handleChange3} />
I just want to have one handleChange
When you need to handle multiple controlled input elements, you can add a name attribute to each element and let the handler function choose what to do based on the value of event.target.name.
For example:
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<form>
<label>
value1:
<input
name="value1"
type="checkbox"
checked={this.state.value1}
onChange={this.handleInputChange} />
</label>
<br />
<label>
value2:
<input
name="value2"
type="number"
value={this.state.value2}
onChange={this.handleInputChange} />
</label>
<br />
<label>
value3:
<input
name="value3"
type="text"
value={this.state.value3}
onChange={this.handleInputChange} />
</label>
</form>
);
}
}
If you add a name to the input you can use that off of the event.
handleChange1(event) {
const {name, value} = event.target
this.setState({[name]: value});
}
<input name="inputone" type="text" value={this.state.value1} onChange={this.handleChange1} />
<input name="inputtwo" type="text" value={this.state.value2} onChange={this.handleChange2} />
<input name="inputthree" type="text" value={this.state.value3} onChange={this.handleChange3} />
You can simply do by using input name:
Code:
import React from "react";
import "./styles.css";
class MyComponent extends React.Component {
state = {
value1: "",
value2: "",
value3: ""
};
handleChange = (event) => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
console.log(this.state);
return (
<>
<input
name="value1"
value={this.state.value1}
type="text"
value={this.state.value1}
onChange={this.handleChange}
/>
<input
name="value2"
value={this.state.value2}
type="text"
value={this.state.value2}
onChange={this.handleChange}
/>
<input
name="value3"
value={this.state.value3}
type="text"
value={this.state.value3}
onChange={this.handleChange}
/>
</>
);
}
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<MyComponent />
</div>
);
}
Demo: https://codesandbox.io/s/beautiful-brook-p46zs?file=/src/App.js:0-1092
i always do this by switch case
handleChange(event) {
switch (event.target.name) {
case 'name1':
this.setState({ name1: event.target.value });
break;
case 'name2':
this.setState({ name2: event.target.value });
break;
case 'name3':
this.setState({ name3: event.target.value });
break;
default:
break;
}
}
<input type="text" name="name1" value={this.state.value1} onChange={this.handleChange1} />
<input type="text" name="name2" value={this.state.value2} onChange={this.handleChange2} />
<input type="text" name="name3" value={this.state.value3} onChange={this.handleChange3} />
You can use react hooks useState for each field:
const [value1,setvalue1] = useState();
<input type="text" value={value1} onChange={(e)=>setvalue1(e.target.value)}/>
You still do have handle change to each input but you write less code.
You can also look here for more info about react hooks: https://reactjs.org/docs/hooks-state.html
If all inputs are same, I think we can render them dynamically so we don't need to repeat ourself and also make the code more clean.
I think we can have an array of inputs then render dynamically. By using closure, we can have one handleChange function for all inputs.
state={
inputValues: []
}
handleChange(index){
return (event)=>{
this.state.inputValues[index] = event.target.value;
this.setState({inputValues: this.state.inputValues})
}
}
render(){
return this.states.inputValues.map((inputValue, index)=>
<input type="text" value={inputValue} onChange={this.handleChange(index)} />
)
}
I am trying to catch 2 input field's value but none of the input fields is working.
when I comment second Input field than the first one works properly.
state = { zipcode: null, city: "" };
onFormSubmit = event => {
event.preventDefault();
//Callback
this.props.onEnter(this.state.zipcode);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
};
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
</form>
</div>
);
}
}
When I hit enter after entering a query in the first input field I get no output and no error.
I tried below code and it worked just fine. Maybe there is something wrong with your callback function. Because on form submission you are getting the correct values.
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
zipcode: null,
city: ""
}
}
onFormSubmit = event => {
event.preventDefault();
//Callback
console.log(this.state);
};
handleChange = event => {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input
type="number"
className={`form-control`}
placeholder="Enter ZIP code"
name="zipcode"
onChange={this.handleChange} />
<input
type="text"
className={`form-control`}
placeholder="Enter Zip-code"
name="city"
onChange={this.handleChange}/>
<input type="submit" value="submit" />
</form>
</div>
);
}
}
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
Here is the jsfiddle link with your code. Check in the inspect element after clicking on the submit button.
It works.
https://jsfiddle.net/t4o0xawr/1/
I have two input boxes to take user input as numbers and want to display their addtion as a result in span but they are not added they are appended.
This is my reactjs that i have tried:
class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value:'',
fno:'',
sno:'',
};
this.handleSquareChange = this.handleSquareChange.bind(this);
this.handleTextChange = this.handleTextChange.bind(this);
this.handleTextLastChange = this.handleTextLastChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSquareChange(event) {
this.setState({value: event.target.value});
}
handleTextChange(event) {
this.setState({fno: event.target.value});
}
handleTextLastChange(event) {
this.setState({sno: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
alert("welcome");
}
render() {
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input type="text" value={this.state.value} onChange=
{this.handleSquareChange} />
<span>First no:</span>
<input type="text" value={this.state.fno} onChange=
{this.handleTextChange} />
<span>second no:</span>
<input type="text" value={this.state.sno} onChange=
{this.handleTextLastChange} />
<input type="submit" value="Submit" onClick={this.handleSubmit} />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{this.state.value * this.state.value}</div>
</div>
<div className="preview">
<h1>Result of no is</h1>
<div>{this.state.fno + this.state.sno}</div>
</div>
</div>
);
}
}
ReactDOM.render(<EssayForm />, document.getElementById('app'));
I have taken a input box to square a number it works fine but not addition.Anybody can let me know where i am wrong.I am new to reactjs.
In your state you have defined sno and fno as string. Therefore when you set anything to them they make the value as string. What you can do is make sno and fno filed as number by giving them the default value of 0. Or, you can typecast them to number before adding. Like, (Number)this.state.fno + (Number)this.state.sno.
handleTextChange(event) {
this.setState({fno: Number(event.target.value)});
}
handleTextLastChange(event) {
this.setState({sno: Number(event.target.value)});
}
just replace the functions.Hope this will solve your problem
This is code for you;
class EssayForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value:'',
fno:'',
sno:'',
};
this.handleChange = this.handleChange(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
const { name, value } = event.target;
this.setState({ [name]: value });
}
handleSubmit(event) {
event.preventDefault();
alert("welcome");
}
render() {
const { fno, sno, value } = this.state;
return (
<div className="example">
<form onSubmit={this.handleSubmit}>
<span>Square of:</span>
<input
type="text"
name="value"
value={value}
onChange={this.handleChange}
/>
<span>First no:</span>
<input
name="fno"
type="text"
value={fno}
onChange={this.handleChange}
/>
<span>second no:</span>
<input
type="text"
name="sno"
value={sno}
onChange={this.handleChange}
/>
<input type="submit" value="Submit" onClick={this.handleSubmit} />
</form>
<div className="preview">
<h1>Square of no is</h1>
<div>{Number(value) * Number(value)}</div>
</div>
<div className="preview">
<h1>Result of no is</h1>
<div>{Number(fno) + Number(sno)}</div>
</div>
</div>
);
}
}
ReactDOM.render(<EssayForm />, document.getElementById('app'));
The constructor and function:
constructor(props) {
super(props);
this.state = {
tagline: 'We rank what people are talking about.',
year: new Date().getFullYear()
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
console.log('onFormSubmit', e)
console.log('this.state', this.state);
};
The form (classNames removed for clarity):
<form onSubmit={ this.onFormSubmit }>
<div className="fl w100">
<div>
<input type="text" id="email" value={ this.state.email }/>
<label htmlFor="email">Email</label>
</div>
</div>
<div className="fl w100">
<div>
<input type="password" id="password" value={ this.state.password }/>
<label htmlFor="password">Password</label>
</div>
</div>
<button type="submit">
Login
</button>
</form>
This is what logs out, note no email or password information:
Full Login component code
import React from 'react';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
tagline: 'We rank what people are talking about.',
year: new Date().getFullYear()
};
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(e) {
console.log('onFormSubmit', e)
console.log('this.state', this.state);
};
render() {
return (<div className="app">
<div className="welcome">
<header>
<div className="wikitags-logo">
<img src="imgs/wikitags-logo.png"/>
</div>
<h2>Admin Portal</h2>
<p>{ this.state.tagline }</p>
</header>
<section className="login-form">
<form onSubmit={ this.onFormSubmit }>
<div className="fl w100">
<div className="mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" type="text" id="email" value={ this.state.email }/>
<label className="mdl-textfield__label" htmlFor="email">Email</label>
</div>
</div>
<div className="fl w100">
<div className="mdl-textfield mdl-js-textfield">
<input className="mdl-textfield__input" type="password" id="password" value={ this.state.password }/>
<label className="mdl-textfield__label" htmlFor="password">Password</label>
</div>
</div>
<button type="submit" className="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
Login
</button>
</form>
</section>
<footer>
© { this.state.year } WikiTags
</footer>
</div>
</div>);
}
}
export default Login;
Suggestions:
1. You are using value property with input fields but you didn't defined the onChange method so your input fields will be read-only because state value will not get updated.
2. You need to define a onChange event will all the input fields or make them uncontrolled element by removing the value property.
3. In case of uncontrolled element define the ref to each field and to access the value use this.ref_name.value.
By Defining the onChange event:
Define the name property to each input element (name should be same as state variable name it will help to update the state and we can handle all the change in single onChange function) like this:
<input type="text" name='value' value={this.state.value} onChange={(e) => this.handleChange(e)} />
handleChange(e){
this.setState({[e.target.name]: e.target.value})
}
By Uncotrolled element:
<input type="text" ref={el => this.el = el} />
Now inside onSubmit function use this.el.value to access he values of this input field.
Check this answer for reference: https://stackoverflow.com/a/43695213/5185595
You are not getting email or password information because you're passing in the state console.log('this.state', this.state); and you haven't set a state for the email and password.
Now, you got two options:
Set the state and get the form info from there
Pass the input value to a function that handles the info
For option 1, you'll need to set a state for your email and password (although setting a state for a password is not recommended) and an onChange event handler on the input(s).
Set up your onChange event handlers.
<form onSubmit={ this.onFormSubmit }>
<input type="text" id="email" onChange={this.handleEmailChange} value={ this.state.email } />
<input type="password" id="password" onChange={this.handlePasswordChange} value={ this.state.password } />
<button type="submit">
Login
</button>
</form>
And the functions to set the email and password states.
handleEmailChange(event) {
this.setState({ email: event.target.value });
}
handlePasswordChange(event) {
this.setState({ password: event.target.value });
}
And don't forget to initialize the state for your email and password in the constructor and bind the functions.
constructor(props) {
super(props);
this.state = {
email: '',
password: ''
};
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
And you're done! Then on the onFormSubmit function just access the email and password values from the state this.state.email and this.state.password and do whatever you like.
Now for option 2, you can just pass in the event.target.value of the inputs, those are the values for the email and the password, and pass those values to a form event handler onSubmit function, from there you can do whatever you want (set the state or update the email and password, change them, whatever).
<form onSubmit={ this.onFormSubmit }>
<input type="text" id="email" name="theEmail" />
<input type="password" id="password" name="thePassword" />
<button type="submit">
Login
</button>
</form>
And the onFormSubmit function.
onFormSubmit(event) {
const email = event.target.theEmail.value;
const password = event.target.thePassword.value;
// do stuff
console.log('Email:', email);
console.log('Password:', password);
};
The easier and recommended way to accomplish what you're trying to do is the option 2.
Remember, the less state your app handles the better.
So how I would approach this is to store the values in your state using what is called a controlled component. Making a controlled component is very simple, this is a basic implementation:
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('A name was submitted: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
The key here is the handleChange function, and the onChange attribute. Every time the input field changes, the handleChange function is going to be called and the state will be updated.
You can find more info form the documentation here: https://facebook.github.io/react/docs/forms.html