0

thanks for taking time to look at my code, I am using React.js to create a search bar, everything works fine until I try to bind inputChange inside the constructor. Once onInputChange is bind in the constructor I cannot type in the form text field. I try console.log and it shows that the event key strokes are captured but nothing show up in the text input field.

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';

    class SearchBar extends Component {
        constructor(props) {
            super(props);
            this.state = { term: '' }; 

            this.onInputChange = this.onInputChange.bind(this); *(if I comment out onInputChange bind statement then I can type in the form field) 

            this.onFormSubmit = this.onFormSubmit.bind(this);
        }

        onInputChange(event) {
            console.log(event.target.value);
            this.setState = ({ term: event.target.value }); 
        }

        onFormSubmit(event) {
            event.preventDefault();
            this.props.fetchWeather(this.state.term);
            this.setState({ term: '' });
        } 

        render() {
            return (    
            <form onSubmit={this.onFormSubmit} className="input-group">
                <input type="text" 
                    placeholder="Five day forcast for your favorite cities" 
                    className="form-control" 
                    value={this.state.term} 
                    onChange={this.onInputChange} /> *(tried this.onInputChange.bind(this) but same thing happened)

                <span className="input-group-btn">
                    <button type="submit" className="btn btn-   secondary">Submit</button>
                </span>
            </form>
            );
        }
    }

    function mapDispatchToProps(dispatch) {
        return bindActionCreators({ fetchWeather }, dispatch);
    }

    export default connect(null, mapDispatchToProps)(SearchBar);

1 Answer 1

1

Why do you assign an object to setState method? Then this.term is never changed.

onInputChange(event) {
  console.log(event.target.value);
  this.setState({ term: event.target.value }); // <-- fixed it
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much!!! it works! it is a silly mistake but I've spent hours banging my head against the wall without catching it. Again, I really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.