1

I'm pretty new to React. I have a simple app where text is entered into an input field and then sent to a server when a button is clicked. How can I get the value of the input field? This is incredbily easy in jQuery but I can't figure it out with React.

Here's my code:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props){
        super(props)

        this.state = {
          terms: ''
        }

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

    updateTerms(evt) {
        this.setState({
            terms: evt.target.value
            })
    }

    search() {

        alert(this.state.terms)
    }

    render() {

    const btn1 = {
      width: '100%',
      backgroundColor: 'white'
    }


    return (
      <div className= 'wrapper'>
        <div className= 'item1'>
          Specials Fact Tree Demo
            </div>
        <div className= 'item2'>
          Search Term(s):<br/>
            <input className= 'form-control'  type="text" onChange={this.updateTerms} />
              <br/>
                <div id = 'results' >
                  <div id='resultsWrap' >
                    <select className= 'form-control' id= 'styles' ></select>
                  <select className= 'form-control' id= 'similar' ></select>

                <div id= 'attsDiv' className= 'form-control' >
                <dl id= 'atts'></dl>
              </div>
                </div>



            </div>
          <button className="btn btn-default" style = {btn1} id= 'search' onClick={this.search}>Search</button>
          <div id="activeTraining" >

            </div>
          </div>
        </div>
    );
  }
}

export default App;

Any help would be greatly appreciated. Plus, easy points!

2
  • Is it not working? Commented Jun 6, 2018 at 13:59
  • No, it keeps saying "cannot get value of undefined". Commented Jun 6, 2018 at 14:01

2 Answers 2

1

You forgot to bind the search method as well (inside the constructor):

this.search = this.search.bind(this);
Sign up to request clarification or add additional context in comments.

2 Comments

Wow.... thanks. Like I said, easy points. I'll accept your answer when the minimum time expires.
hehe that was fun
0

If you are already familar with ECMAScript 6 you can just use arrow functions and save on the bindings like:

search = () => {
   alert(this.state.terms)
}

Comments

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.