简体   繁体   中英

Get search value in state in ReactJS

I am new in ReactJS and trying to get the search input box value and store it in a state.

My code:

<form className="search-form" onSubmit={this.handleSubmit}>
      <input type="search" name="search" ref={(input) => this.query = input}
                               placeholder="Search..." />
      <button className="search-button" type="submit" id="submit">Go!</button>
</form>

Inside constructor:

this.handleSubmit = this.handleSubmit.bind(this);

And

handleSubmit = e => {
        e.preventDefault();
        this.setState({search: this.query.value});
        console.log(this.state.search) //Returns undefined
        e.currentTarget.reset();
    }

Any help is highly appreciated.

I would suggest you to use controlled input approach.

state = {
   value: null,
}

handleValue = (e) => this.setState({ value: e.target.value });

Then you don't have to use ref .

<input 
   type="search" 
   name="search" 
   onChange={this.handleValue}
   placeholder="Search..." 
/>

This code may help you:

import React from 'react';
class search extends React.Component{
    constructor(props)
    {
      super(props);
      this.state = {value: ''};
      this.addValue = this.addValue.bind(this);
      this.updateInput = this.updateInput.bind(this);
    }

    addValue(evt)
    {
      evt.preventDefault();
      if(this.state.value !==undefined)
      {
        alert('Your input value is: ' + this.state.value)
      }
    }
    updateInput(evt){
      this.setState({value: evt.target.value});   
        }

    render()
    {
      return (
      <form onSubmit={this.addValue}>
      <input type="text" onChange={this.updateInput} /><br/><br/>
      <input type="submit" value="Submit"/>
      </form>
      )
    }
}
export default search;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM