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'));
Related
I have assigned default values to the input tag. When I try to submit without changing the values of the input tag, the value passed is undefined.
What I want is that if the input value is changed, to update the state value with the new value and if the input tag value is not changed, then to pass the default value to the state.
I am new to React.
import React, { Component } from 'react';
import Firebase from '../Firebase';
import _ from 'lodash';
import '../App.css';
class Modify extends Component {
constructor(props) {
super(props);
//state
this.state = {
personDetails: {},
detail: ''
};
//bind
this.renderData = this.renderData.bind(this);
this.handleChange = this.handleChange.bind(this);
this.saveEdit = this.saveEdit.bind(this);
}
//lifecycle
componentDidMount() {
Firebase.database().ref('/nannydetails').on('value', (snapshot) => {
this.setState({
personDetails: snapshot.val()
})
})
}
//handle change
handleChange(event) {
this.setState({
[event.target.name]: event.target.value.toLowerCase()
});
}
//render data
renderData() {
return _.map(this.state.personDetails, (personDetail, key) => {
return(
<div className="pt-2 pb-1 m-2 border border-dark bg-warning row" key={key}>
<div className="col-md-3 col-xs-3 text-right">
<img src={require('./profile.png')} alt="cam"/>
</div>
<div className="col-md-9 col-xs-9 p-2">
<div className="headline">
<h1>Full Name: </h1>
<input className="form-control" type="text" name="fullName" defaultValue={personDetail.fullname} onChange={this.handleChange}/>
</div>
<div className="headline">
<h1>Contact Number: </h1>
<input className="form-control" type="text" name="phone" defaultValue={personDetail.phone} onChange={this.handleChange}/>
</div>
<div className="headline">
<h1>Experience: </h1>
<input className="form-control" type="text" name="experience" defaultValue={personDetail.experience} onChange={this.handleChange}/>
</div>
<div className="headline">
<h1>City: </h1>
<input className="form-control" type="text" name="city" defaultValue={personDetail.city} onChange={this.handleChange}/>
</div>
<div className="headline">
<h1>State: </h1>
<input className="form-control" type="text" name="state" defaultValue={personDetail.state} onChange={this.handleChange}/>
</div>
<button className="btn btn-success" type="button" onClick={() => this.saveEdit(key)}><i className="fa fa-pencil-square-o"></i> Save Edit</button>
<button className="btn btn-danger" type="button" onClick={() => this.handleDelete(key)}><i className="fa fa-trash"></i> Delete</button>
</div>
</div>
)
});
}
//handle save edit
saveEdit(key) {
// Firebase.database().ref(`/nannydetails/${key}`).push({
// fullname: this.state.fullname,
// phone: this.state.phone,
// experience: this.state.experience,
// city: this.state.city,
// state: this.state.state
// });
console.log(this.state.fullname);
console.log(this.state.phone);
console.log(this.state.experience);
console.log(this.state.city);
console.log(this.state.state);
}
//handle delete
handleDelete(key) {
const user= Firebase.database().ref(`/nannydetails/${key}`);
user.remove();
}
render() {
return (
<div className="container mt-4">
{this.renderData()}
</div>
);
}
}
export default Modify;
Update the change handler to update/mutate the existing state instead of adding a new property(key), i.e. on this.state.personDetails.X vs. this.state.X
//handle change
handleChange(event) {
// update the personDetails object you set in state on mount
const newPersonDetails = { ...this.state.personDetails };
newPersonDetails[event.target.name] = event.target.value.toLowerCase();
this.setState({
personDetails: newPersonDetails,
});
}
Make this as a controlled component. Provide a initial state in you component and all the updated will done into the state & that will directly reflect into your component.
Initial State:
this.state = {
personDetails: {
fullname :'test'
},
detail: ''
};
Input Field
input className="form-control" type="text" name="fullName" value={this.state.personDetail.fullname} onChange={this.handleChange}
onChange is only triggered when the value of input changes. The defaultValue can be defined in the initial state, and the defaultValue is overwritten when the value of input changes.
The best way to approach is to have a main component take data from any api (firebase in your case) and second child component which will be responsible to take input as props and return input(default/modified) on form action(submit). That way if data changes you get modified data else the default one.
class FormComp extends React.Component {
constructor(props) {
super(props);
this.state = {
name: this.props.form.name,
};
this.submit = this.submit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
submit(e) {
e.preventDefault();
console.log(this.state);
}
handleChange(e) {
this.setState({name: e.target.value});
}
handleChan
render() {
return (
<div>
<form onSubmit={this.submit}>
<input
type="text"
value={this.state.name}
onChange={this.handleChange}
/>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
Refer to that fiddle for example. https://jsfiddle.net/papish19/ys6utv3k/7/
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 am facing a problem with the select list the onChange event is not being triggered. I can't set the value selected from the select list in this.state variable. Any help will be appreciated.
class SelectActivity extends React.Component{
render(){
return (
<select value={this.props.value} onChange={() =>{this.props.onSelect()}}> {this.props.items.map((item,index) =>{
return <option value={index}>{item}</option>})}
</select>
)
}
}
class Form extends React.Component{
constructor(props){
super(props)
this.state = {first:"",last:"",activity:0,restriction:{a:false,b:false,c:false}}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
this.setState({[event.target.name]:event.target.value},()=>{console.log(this.state)})
}
handleCheck(key) {
return function (event) {
var restriction = Object.assign({},this.state.restriction);
restriction[key] = event.target.checked;
this.setState({restriction:restriction},()=>{console.log(this.state)});
}.bind(this);
}
render(){
return(
<form>
<div>
First Name<input name="first" value={this.state.first} onChange={this.handleChange}/>
</div>
<div>
Last Name<input name="last" value={this.state.last} onChange={this.handleChange}/>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.a} onChange={this.handleCheck("a")}/>
<label>a) Dietarty Restriction</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.b} onChange={this.handleCheck("b")}/>
<label>b) Physical Disablities</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.c} onChange={this.handleCheck("c")}/>
<label>c) Medical Needs</label>
</div>
<div>
<SelectActivity name="activity" items={["Science Lab","Swimming","Painting","Cooking"]} value={this.state.activity} onSelect={this.handleChange}/>
</div>
</form>
)
}
}
ReactDOM.render(
<Form/>,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>
You are not sending the event that is triggered on change of your select input, but you are just calling the function with
onChange={ () => {this.props.onSelect()} }
Also, you didn't have any name assigned to your select input.
Please update your select input to:
<select
value={this.props.value}
name={this.props.name}
onChange={this.props.onSelect} // assigning the function, so it can be trigged with all argument
>
{
this.props.items.map((item,index) => {
return <option value={index}>{item}</option>
})
}
</select>
class SelectActivity extends React.Component{
render(){
return (
<select value={this.props.value} name={this.props.name} onChange={this.props.onSelect}> {this.props.items.map((item,index) =>{
return <option value={index}>{item}</option>})}
</select>
)
}
}
class Form extends React.Component{
constructor(props){
super(props)
this.state = {first:"",last:"",activity:0,restriction:{a:false,b:false,c:false}}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event){
this.setState({[event.target.name]:event.target.value},()=>{console.log(this.state)})
}
handleCheck(key) {
return function (event) {
var restriction = Object.assign({},this.state.restriction);
restriction[key] = event.target.checked;
this.setState({restriction:restriction},()=>{console.log(this.state)});
}.bind(this);
}
render(){
return(
<form>
<div>
First Name<input name="first" value={this.state.first} onChange={this.handleChange}/>
</div>
<div>
Last Name<input name="last" value={this.state.last} onChange={this.handleChange}/>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.a} onChange={this.handleCheck("a")}/>
<label>a) Dietarty Restriction</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.b} onChange={this.handleCheck("b")}/>
<label>b) Physical Disablities</label>
</div>
<div>
<input type="checkbox" checked={this.state.restriction.c} onChange={this.handleCheck("c")}/>
<label>c) Medical Needs</label>
</div>
<div>
<SelectActivity name="activity" items={["Science Lab","Swimming","Painting","Cooking"]} value={this.state.activity} onSelect={this.handleChange}/>
</div>
</form>
)
}
}
ReactDOM.render(
<Form/>,
document.getElementById("root")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
<div id="root"></div>
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>
);
}
}
I have the below input fields of which I need to get the entered inputs and pass it to the onClick event of the button shown below.
<input type="text" style={textFieldStyle} name="topicBox" placeholder="Enter topic here..."/>
<input type="text" style = {textFieldStyle} name="payloadBox" placeholder="Enter payload here..."/>
<button value="Send" style={ buttonStyle } onClick={this.publish.bind(this,<value of input field 1>,<value of input field2>)}>Publish</button><span/>
I have a method called publish which takes two string arguments. In place of those strings, I need to pass the values entered in the input fields. How can I achieve this without storing the values in states? I do not want to store the input field values in state variables. Any help would be much appreciated.
How can I achieve this without storing the values in states?
I think in this case better use states
class App extends React.Component {
constructor() {
super();
this.state = {
topicBox: null,
payloadBox: null
};
this.publish = this.publish.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange({ target }) {
this.setState({
[target.name]: target.value
});
}
publish() {
console.log( this.state.topicBox, this.state.payloadBox );
}
render() {
return <div>
<input
type="text"
name="topicBox"
placeholder="Enter topic here..."
value={ this.state.topicBox }
onChange={ this.handleChange }
/>
<input
type="text"
name="payloadBox"
placeholder="Enter payload here..."
value={ this.state.payloadBox }
onChange={ this.handleChange }
/>
<button value="Send" onClick={ this.publish }>Publish</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<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>
<div id="container"></div>
You can add ref for each text field, and read the value from it like:
class App extends React.Component {
constructor() {
super();
this.publish = this.publish.bind(this);
}
publish(topicBox, payloadBox) {
alert(this.refs.topic.value);
alert(this.refs.payload.value);
}
render() {
return <div>
<input
ref="topic"
type="text"
name="topicBox"
placeholder="Enter topic here..."/>
<input
ref="payload"
type="text"
name="payloadBox"
placeholder="Enter payload here..."/>
<button
value="Send"
onClick={this.publish}>
Publish
</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('container'));
Working fiddle https://jsfiddle.net/hjx3ug8a/15/
Thanks for Alexander T for his addition!