1

Tried to get input's value when user click search but failed.

var Login = React.createClass({
  getInitialState: function () {
    return {name: ''};
  },
  handleSearch(){
    alert(this.state.name); // doesn't work?
  },
  handleChange(e){
    this.setState({name: e.target.value});
  },
  render() {
    return <div>
      <input type="text" placeholder="name" onChange="{this.handleChange}" value=""/><button onClick={this.handleSearch}>Search</button>
    </div>;
  }
})

is there any more straight forward to get the value of input?

1 Answer 1

4

The principal issue is that you have quotes around your onChange:

onChange="{this.handleChange}"

it shouldn't have them, that's setting it to a string value. Just:

onChange={this.handleChange}

(as you did with onClick on the button).

You'll also need to set value to this.state.name:

var Login = React.createClass({
  getInitialState: function () {
    return {name: ''};
  },
  handleSearch(){
    console.log("name is", this.state.name);
  },
  handleChange(e){
    this.setState({name: e.target.value});
  },
  render() {
    return <div>
      <input type="text" placeholder="name" onChange={this.handleChange} value={this.state.name} /><button onClick={this.handleSearch}>Search</button>
    </div>;
  }
});

ReactDOM.render(
  <Login />,
  document.getElementById("react")
);
<div id="react"></div>
<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>

Sign up to request clarification or add additional context in comments.

3 Comments

@NatelyJamerson: How does that relate to this question?
it doesn't but can you please take a look? :D
@NatelyJamerson: I'm afraid not. I don't use CodePen, and I don't (directly) use RequireJS, so I wouldn't be much 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.