ReactJs input first value getting empty - reactjs

import React, { Component } from "react";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log(this.state.value);
this.setState({ value: event.target.value });
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
console log screenshot
I'm getting first input value empty. I have different app. I'm basically try to doing tip calculator app. I don't need submit button. The user will enter a value, but it does not calculate correctly because the first value is empty. At the same time, it does not show the last value entered, only when clicked, all the entered values are correct. By the way, i got this form from React own site, but it's the same error that i encountered. Thank you!

Your console.log logs the value before you change it. Thus it will always be the previous value.
You also have to keep in mind that the Component.setState method might not execute immediately.
Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.
Therefore you should use a callback. E.g.
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
Here is an executable example. Click Run code snippet.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Set initial value to 0 so that it will not be empty.
this.state = { value: 0 };
Also move your console.log as callback function to setState so that you can see the updated value.
import React, { Component } from "react";
export default class App2 extends React.Component {
constructor(props) {
super(props);
this.state = { value: 0 };
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value }, () => {
console.log(this.state.value);
});
}
render() {
return (
<form>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}

Related

Why value of input here at reactjs is undefined?

I want to change state by the value of input but it is undefined.
It should work, the value is for every HTML tag so what is wrong with my code??
import React, { Component } from "react";
class App extends Component {
constructor() {
super();
this.state = {
firstName: " "
};
this.handleChange = this.handleChange(this);
}
handleChange(event) {
this.setState({
firstName: event.target.value
});
}
render() {
return (
<form>
<input
type="text"
placeholder="Firstname"
onChange={this.handleChange}
/>
<h1>{this.state.value}</h1>
</form>
);
}
}
export default App;
There's no value stored in your state, so it is undefined, and you do not correctly bind this to your handler. Output this.state.firstName instead:
import React, { Component } from "react";
class App extends Component {
constructor() {
super();
this.state = {
firstName: " "
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({
firstName: event.target.value
});
}
render() {
return (
<form>
<input
type="text"
placeholder="Firstname"
onChange={this.handleChange}
/>
<h1>{this.state.firstName}</h1>
</form>
);
}
}
export default App;
First try to bind this for handleChange using an arrow function. Also use the state variable to set the value property of the input .
Sandbox link: https://codesandbox.io/s/react-basic-example-qmyw5
import React, { Component } from "react";
class App extends Component {
constructor() {
super();
this.state = {
firstName: " "
};
}
handleChange = (event) => {
this.setState({
firstName: event.target.value
});
}
render() {
return (
<form>
<input
type="text"
placeholder="Firstname"
onChange={this.handleChange}
value={this.state.firstName}
/>
<h1>{this.state.firstName}</h1>
</form>
);
}
}
export default App;

How to assign a value of a variable from a function in another function in React JS

class App extends React.Component {
constructor (props) {
super(props);
this.state ={val:'test'}
}
change(e){
let valueOfInput = e.target.value;
}
submit(ev){
ev.preventDefault();
alert(valueOfInput)
}
render() {
return(
<div>
<form action="">
<input onChange={this.change.bind(this)} type="text" value={this.state.val}/>
<input onClick={this.submit.bind(this)} type="submit" value='submit'/>
</form>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="root"> </div>
With this code i want to send the value of the input in alert from sumbit() function. So, i want to take the value from input, to save it in variable valueOfInput, and after that to send that value in alert from submit function. How to realize that in ReactJs?
How about using state!!
setState() enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
class App extends React.Component {
constructor (props) {
super(props);
this.state ={valueOfInput:''}
}
change(e){
valueOfInput = e.target.value;
this.setState({valueOfInput});
}
submit(ev){
ev.preventDefault();
alert(this.state.valueOfInput)
}
render() {
return(
<div>
<form action="">
<input onChange={this.change.bind(this)} type="text" value={this.state.valueOfInput}/>
<input onClick={this.submit.bind(this)} type="submit" value='submit'/>
</form>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
Happy coding!!! Hope this helps.
Storing value of input in valueOfInput variable can be done by declaring it into class level using this.
constructor(props) {
super(props);
this.state = { val: "test" };
this.valueOfInput = null;
}
change(e) {
this.valueOfInput = e.target.value;
}
submit(ev) {
ev.preventDefault();
alert(this.valueOfInput);
}
But it won't work as expected as we're not updating value of input with new value. So to solve this we have to store new input value into state and use that value in input.
change(e) {
this.valueOfInput = e.target.value;
this.setState({
val: e.target.value
});
}
Your valueOfInput seems to be defined in its block space of change(), declare that variable within the class state and you should be able to reference it in the submit() callback.
class App extends React.Component {
constructor (props) {
super(props);
this.state = {
valueOfInput: null,
}
}
change(e){
this.setState({
valueOfInput: e.target.value,
val:e.target.value
});
}
submit(ev){
ev.preventDefault();
alert(this.state.valueOfInput)
}
render() {
return(
<div>
<form action="">
<input onChange={this.change.bind(this)} type="text" value={this.state.valueOfInput}/>
<input onClick={this.submit.bind(this)} type="submit" value='submit'/>
</form>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);

Loading a component after submitting a form

I tried to load a component to my web app after submitting a form. However, the value doesn't persist on the web page for more than a few seconds.
import React,{Component} from 'react';
import Load from './load'
class Form extends Component {
constructor(props) {
super(props);
this.state = {value: '',
showComponent: false,
};
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);
this.setState({
showComponent: true,
});
}
render() {
return (
<div>
<form onSubmit={this._handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
{this.state.showComponent ?
<Load /> :
null
}
</div>
);
}
}
export default Form
The code for Load is as follows
import React,{Component} from 'react';
class Load extends Component {
render() {
return (
<p>hello</p>
)
}
}
export default Load
As I had said, the value of hello doesn't stay on my screen for more than a few seconds. Please help. I am very new to react
Just try preventing default Submit Event of the form this will initiate a GET request and your URL will reload and this will lead to your main component ReRendering and showComponent is being set to false again.
_handleSubmit(event) {
event.preventDefault(); // Add this line to prevent your form's default event.
//alert('A name was submitted: ' + this.state.value);
this.setState({
showComponent: true,
});
}

simple Debounce not working in react 16 but works in jsfiddle with react 14.3

This doesn't work in react 16, but this jsfiddle works fine: https://jsfiddle.net/kp04015o/9/
Can any one debug this error why? Cannot read property 'value' of null, at handleChange = debounce(e => this.setState({searchTerm: e.target.value}), 1000);
import React from 'react';
import ReactDOM from 'react-dom';
const debounce = (cb, wait) => {
let timeout;
return function() {
let callback = () => cb.apply(this, arguments);
clearTimeout(timeout);
timeout = setTimeout(callback, wait);
}
}
class Debounce extends React.Component {
state = {
searchTerm: '',
};
handleChange = debounce(e => this.setState({searchTerm: e.target.value}), 1000);
render() {
return (
<div>
<input type="text" onChange={this.handleChange}/>
<div>Search Value 2: {this.state.searchTerm}</div>
</div>
);
}
}
ReactDOM.render(<Debounce />, document.getElementById('root'));
Read about Event Pooling
Here you have a working code:
class Debounce extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
state = {
searchTerm: '',
};
setSearchTerm = debounce((searchTerm) => this.setState({ searchTerm }), 1000);
handleChange(e) {
this.setSearchTerm(e.target.value);
}
render() {
return (
<div>
<input type="text" onChange={this.handleChange} />
<div>Search Value 2: {this.state.searchTerm}</div>
</div>
);
}
}
or nicer with ES7 decorators and decko module:
import { debounce, bind } from 'decko';
class Debounce extends React.Component {
state = {
searchTerm: '',
};
#debounce(1000)
setSearchTerm(searchTerm) {
this.setState({ searchTerm });
}
#bind
handleChange(e) {
this.setSearchTerm(e.target.value);
}
render() {
return (
<div>
<input type="text" onChange={this.handleChange} />
<div>Search Value 2: {this.state.searchTerm}</div>
</div>
);
}
}
I feel like I know this.
Try changing this:
<input type="text" onChange={this.handleChange} />
to either:
<input type="text" onChange={this.handleChange.bind(this)} />
or:
<input type="text" onChange={(e) => this.handleChange(e)} />
That is my gut reaction every time I see something of undefined with a React event, and because your default state is handled. If this works, it's because the execution context or lexical environment is in a different dimension than it might appear.

React - setState not resetting input

Following my first React tutorial. My code seems to be exactly like the tutorial, but my input doesn't reset within a form component. The first time I submit, everything works fine, but the state holds onto the first value. Even when calling setState with a console.log in a callback, it seems like setState doesn't even fire. this is bound in my constructor function.
import React, { Component } from 'react';
import TenantActions from '../actions/TenantActions';
export default class AddTenantForm extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
}
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
console.log('1. On Submit click, sending addNewTenant action w/', this.state);
TenantActions.addNewTenant(this.state);
this.setState = ({ name: '' });
}
render() {
return (
<form>
<div className="form-group">
<input type="text"
className="form-control"
id="tenantName"
placeholder="Bob Smithers"
value={this.state.name}
onChange={e => this.setState({ name: e.target.value })}
/>
</div>
<button className="btn btn-default"
onClick={this.onSubmit}
>Submit</button>
</form>
)
}
}
this.setState is a function. You have a typo (= extra) in the function onSubmit.
Replace this.setState = ({...}) with this.setState({name: ''})
More about setState

Resources