please help me wit this code. I am struggling to update state right away after input is inserted. I was trying to do it with onSubmit method at least to sync input === submit after clicking on Button but still no luck as per console log.
See console picture:
enter image description here
How should I do it?
import React from 'react';
import './Search.css';
const results = ["Balaton", "Zamardi", "Sound", "Madarsko", "Sziget", "Hungary"]
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
submit: ''
};
this.onInput = this.onInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onInput(event) {
this.setState({
input: event.target.value,
submit: this.state.input});
console.log(this.state.input)
console.log(this.state.submit)
}
onSubmit(event) {
event.preventDefault()
if (results.includes(this.state.input)){
return alert("This is correct")
} else {
return alert("This not correct")
}
}
render() {
return(
<div>
<form className="search-form" onSubmit={this.onSubmit}>
<input type="text" value={this.state.input} placeholder="Our great memory" onChange={this.onInput}/>
<button type="submit">Try that!</button>
</form>
</div>
)
}
};
export default Search;
I re-wrote your component for readability, I believe you error is simply that setstate is async. This means that when you tried to set the state of submit at the same time as input, submit would always be one behind. By adding the callback in onInput after input has been set you should get the correct value ready to be submitted
import React, { Component } from 'react';
const results = ["Balaton", "Zamardi", "Sound", "Madarsko", "Sziget", "Hungary"]
class Search extends Component {
state = {
input: '',
submit: ''
};
// Added callback after input setstate
onInput = (event) => {
this.setState({
input: event.target.value}, () => this.setState({submit: this.state.input));
console.log(this.state.input)
console.log(this.state.submit)
}
onSubmit = (event) => {
event.preventDefault()
if (results.includes(this.state.input)){
return alert("This is correct")
} else {
return alert("This not correct")
}
}
render() {
return(
<div>
<form className="search-form" onSubmit={this.onSubmit}>
<input
type="text"
value={this.state.input}
placeholder="Our great memory"
onChange={this.onInput}/>
<button type="submit">Try that!</button>
</form>
</div>
)
}
};
export default Search;
onInput(event) {
this.setState({
input: event.target.value,
submit: event.target.value});,() =>
console.log(this.state.input)
console.log(this.state.submit)
}
This will let you see the correct values in log too.
Your submit state doesn't update as you assign the old value of this.state.input to it rather you should assign event.target.value.
Related
I'm trying to use ReactJS, and I have encountered this problem:
I have a simple for with one field. And when I click on the submit button the page complete the code but immediately reload (i don't event have the time to read the console).
const INITIAL_STATE = {
teamName: '',
error: null,
};
class SearchingForm extends Component {
constructor(props){
super(props);
this.state = {
...INITIAL_STATE,
results: []
};
}
onSubmit = event => {
const { teamName } = this.state;
this.searching(this.state.teamName)
event.preventDefaul();
}
searching(teamName){
console.log("teamName: ", teamName)
}
onChange = event => {
this.setState({ [event.target.name]: event.target.value });
console.log(this.state)
};
render() {
const {
teamName,
error
} = this.state;
const isInvalid = teamName === '';
return (
<form onSubmit={this.onSubmit}>
<input
name="teamName"
value={teamName}
onChange={this.onChange}
type="text"
placeholder="Team Name"
/>
<button type="submit">Search</button>
</form>
);
}
}
Why do I have this behaviour?
Thank you.
There is a typo in your code
event.preventDefaul();
instead of
event.preventDefault();
and it should be the first line in the onSubmit function.
there is a typo instead of event.preventDefaul(); it should be
event.preventDefault().
and it used to be in the first line of your method.
Firstly you have to call event.preventDefault(); at first line of onsubmit function.
secondly their is typo error in preventDefault
Please use under given code:
onSubmit = event => {
event.preventDefaul();
const { teamName } = this.state;
this.searching(this.state.teamName);
}
I recently got started with React and want to build a little application to fetch weather data. My API has a function to return autocomplete suggestions. So when my autosuggestion array is not empty I render a list and upon clicking one of the <li>'s I want the value inside of the input box. I manage to set the state of my SearchBar but can't change it's value.
Edit: I try to get my value from changeState() into my <input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />. I can search for terms otherwise.
import React from 'react';
import './SearchBar.css';
import Suggestion from './Suggestion';
class SearchBar extends React.Component{
constructor(props) {
super(props);
this.state = {inputValue: ''};
this.search = this.search.bind(this);
this.updateInputValue = this.updateInputValue.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.changeState = this.changeState.bind(this);
}
changeState(value) {
console.log(value);
// Logs value of text between <li></li>
this.setState({inputValue: value});
}
search() {
this.props.onSearch(this.state.inputValue);
}
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
});
this.props.onChange(this.state.inputValue);
}
handleKeyPress(e) {
if(e.key === 'Enter') {
this.search();
}
}
render() {
return (
<div>
<div className="SearchGroup" onKeyPress={this.handleKeyPress} >
<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />
<a onClick={this.search}>Go</a>
</div>
<Suggestion autocomplete={this.props.autocomplete} onSelect={this.changeState} />
</div>
);
}
}
export default SearchBar;
For the sake of completeness my Suggestion.js:
import React from 'react';
import './Suggestion.css';
class Suggestion extends React.Component{
constructor(props) {
super(props);
this.updateInputField = this.updateInputField.bind(this);
}
updateInputField(evt) {
this.props.onSelect(evt.currentTarget.innerText);
}
render(){
if(this.props.autocomplete && this.props.autocomplete.length > 0) {
return (
<div className="Suggestion">
<ul>
{
this.props.autocomplete.map((location) => {
return (
<li key={location.id} onClick={this.updateInputField}>{location.name}</li>
)
})
}
</ul>
</div>
);
} else {
return <div className="None"></div>
}
}
}
export default Suggestion;
I would also prefer to submit location.url in Suggestion, but I could not find a property that matches inside of evt.
As mentioned in my comment. You are setting state and immediately passing state to onChange function in updateInputValue event handler function which is not correct. Because you won't get the state value updated immediately, the state value updates only when it renders so, pass evt.target.value directly like below
updateInputValue(evt) {
this.setState({ inputValue: evt.target.value });
this.props.onChange(evt.target.value);
}
In order to see chnaged value on your input field, you have to pass value prop to input tag like below
<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} value={this.state.inputValue}/>
I would guess that you are trying to use value from state that isnt there yet, because setState is asynchronous
so either use callback on setState
updateInputValue(evt) {
this.setState({
inputValue: evt.target.value
}, ()=> this.props.onChange(this.state.inputValue));
}
or, use the value from event directly
updateInputValue(evt) {
const value = evt.target.value
this.setState({
inputValue: value
});
this.props.onChange(value)
}
plus you havent assigned value back to your input:
<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} value={this.state.inputValue}/>
The React setState doesn't update the state immediately. It puts it in the queue and updates the state in batches. if you want to access the updated state write the code in the setState callBack
this.setState({ inputValue: evt.target.value},()=> this.props.onChange(this.state.inputValue));
something like this
I was trying to handle changing of states whenever I type something inside the two text boxes and then when the user click the button, it will set the state to it's state and then console.log the current change state to the console.
Basically I have this:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
catname: '',
catamt: 0
};
this.addBudget = this.addBudget.bind(this);
}
addBudget(e) {
e.preventDefault();
this.setState({
catname: e.target.value,
catamt: e.target.value
});
console.log('console log catname here.....', this.state.catname);
console.log('console log catamt here.....', this.state.catamt);
}
}
And then inside my component where the form is sitting:
import React from 'react';
export default class AddBudget extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="cat-input">
<input
type="text"
name="categoryname"
placeholder="Budget Category"
/>
<input
type="number"
name="categoryamount"
placeholder="Target Budget"
/>
</div>
<button onClick={this.addBudget}>+</button>
);
}
}
How do I pass along my input value to my function and console log the change of state?
Something more like that, I recommended using controlled input with react.
You can read more about it here https://reactjs.org/docs/forms.html
An example for you :) https://codesandbox.io/s/2486wxkn9n
First you need to keep track on the value with the state. Second with the form you can handle the submit. This way if a user click the button or press enter you can handle the submit method.
Inside the _handleChange method you receive the event. So this is the input change. If you console.log this value you can see he have the name, the name you pass in the input. This way you can use it as a key variable for your object. So one function for 2 :).
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
catname: '',
catamt: 0
};
this.addBudget = this.addBudget.bind(this);
}
addBudget = (e) => {
e.preventDefault();
console.log('console log catname here.....', this.state.catname);
console.log('console log catamt here.....', this.state.catamt);
}
_handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
render() {
return (
<AddBudget handleChange={this._handleChange} addBudget={this.addBudget} />
)
}
}
export default class AddBudget extends React.Component {
render() {
return (
<div className="cat-input">
<form onSubmit={this.props.addBudget}>
<input
type="text"
name="catname"
onChange={this.props.handleChange}
placeholder="Budget Category"
/>
<input
type="number"
name="catamt"
placeholder="Target Budget"
onChange={this.props.handleChange}
/>
<button type="submit">+</button>
</form>
</div>
);
}
}
I have small class in react, i want to display the result on the screen after i click on the button, but before the display happens, the page reload.
how do i do it?
what am I missing?
import React, {Component} from 'react';
class InputFieldWithButton extends Component{
constructor(props){
super();
this.state = {
message: ''
};
}
handleChange(e){
this.setState({
message: e.target.value
});
}
doSomething(e){
return(
<h1>{this.state.message}</h1>
)
}
render(){
return (
<div>
<form >
<input type="text" placeholder="enter some text!" value=
{this.state.message}
onChange={this.handleChange.bind(this)}/>
<button onClick={this.doSomething.bind(this)}>Click me</button>
</form>
</div>
)
}
}
export default InputFieldWithButton;
Your button is inside a form and triggering a submit.
You can use the preventDefault() method to stop it from doing so:
doSomething(e) {
e.preventDefault();
return (
<h1>{this.state.message}</h1>
)
}
By the way, your return statement of this click handler makes no sense at the moment.
Edit
As a followup to your comment:
Can you explain me what is my mistake in the return?
Not really a mistake, but it is useless in this context as your are not doing anything with the returned object.
Where and how do you expect to use the <h1>{this.state.message}</h1> that you are returning?
If you intend to show / hide the input message in your screen you could do it with conditional rendering.
Just store a bool like showMessage in your state and render the message only if it's set to true.
Here is a small example:
class InputFieldWithButton extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
showMessage: false
};
}
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
toggleMessage = (e) => {
e.preventDefault();
this.setState({ showMessage: !this.state.showMessage })
}
render() {
const { showMessage, message } = this.state;
return (
<div>
<form >
<input
type="text"
placeholder="enter some text!"
value={message}
onChange={this.handleChange}
/>
<button onClick={this.toggleMessage}>Toggle Show Message</button>
{showMessage && <div>{message}</div>}
</form>
</div>
)
}
}
ReactDOM.render(<InputFieldWithButton />, document.getElementById('root'));
<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="root"></div>
By the way, it is considered as bad practice to bind the functions inside the render method, because you are creating a new instance of a function on each render call. instead do it inside the constructor which will run only once:
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
Or you can use arrow functions which will reference this in a lexical context:
handleChange = (e) => {
this.setState({
message: e.target.value
});
}
This is what i've used in my example.
you're not specifying the buttons'type
<button type="button">
Set the type attribute on the button to be button. The default is submit since it is wrapped in a form. So your new button html should look like this:
<button type="button" onClick={this.doSomething.bind(this)}>Click me</button>
I'm trying to implement some validation for an email based input. It's mostly there, but I'm running into a strange condition.
I'm debouncing the onChange function that includes some validation and validating again on submit. If the user submits an invalid string before the debounce catches it, the submit function will catch it and set the component state to invalid, but only until the debounce hits, at which point the debounce sets the state back to valid, because it seems like the form submit is clearing out the underlying value of the input field. I have a preventDefault in my submit function, but it still seems like the event.target is getting emptied whenever that submit function is fired. I would like to keep the event.target/input value in sync. Here is my code:
import React from 'react';
import {Link} from 'react-router';
import _ from 'underscore';
import classNames from 'classnames';
class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
isValid: true
};
this.validateOnChange = _.debounce(this.validateOnChange,500).bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.validateEmail = this.validateEmail.bind(this);
}
handleSubmit(event) {
event.preventDefault();
if(this.validateEmail(event.target[0].value)){
$.ajax({
url: '/api/search?email=' + event.target[0].value
})
.done((data) => {
this.props.getNewImage(data, false);
})
.fail(() => {
this.props.getNewImage('/img/obi.gif', true);
});
}else {
this.setState({isValid: false});
}
}
validateOnChange(event){
this.setState({isValid: (event.target.value ? this.validateEmail(event.target.value) : true)});
}
validateEmail(input){
var re;
re = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)\b/i;
return re.test(input);
}
render() {
var classes = classNames({
'form-control': true,
'valid': this.state.isValid,
'invalid': this.state.isValid === false
});
return(
<form ref='searchForm' className='navbar-form navbar-left animated' onSubmit={this.handleSubmit.bind(this)}>
<div className='input-group'>
<input type='text' className={classes} placeholder="Enter Email!" onChange={this.validateOnChange.bind(this)} />
<span className='input-group-btn'>
<button className='btn btn-default' type="submit"><span className='glyphicon glyphicon-search'></span>Search</button>
</span>
</div>
{this.state.isValid ? null : <span className="invalid-text">Invalid Email Address</span> }
</form>
);
}
}
export default Search;
you can use linkState of react/linkState to handle the onChange event of an input element.
<input
min="1"
max="10"
type="number"
className="form-control"
valueLink={linkState(this, 'qty')} />