1

I have a form on my React site and I am trying to get the data that a user enters. I have followed the documentation here, and a similar Stack Overflow post here, and when I press the submit button, I get the alert message. However, it doesn't let me type anything in the input field.

My code:

class Search extends Component {
    constructor(props) {
        super(props);
        this.state = { value: "" };

        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 (
            <div className="Search">
                <form className="searchBox" onSubmit={this.handleSubmit}>
                    <input type="text" value={this.state.value}/>
                    <input type="submit" value="Go" />
                </form>
            </div>
        );
    }
}
SirArchibald
  • 476
  • 2
  • 7
  • 23

1 Answers1

0

If you are using default form setup of react then you need to use onChange handler for every input field and also maintain states for those fields too but in my opinion you should use Formik as it provides way more functionalities than default react form setup and also form validations. But to give you an answer of your question - Use onChange handler for your input field and during submission access those input handler states.

Piyush Rana
  • 631
  • 5
  • 8