5

I've been trying to take inputs from an input field and i used refs(the usual way in react), But it doesn't seem to be working. The input i'm getting is undefined. This is my code:

sendMessage = () => {
   console.log(this.inputtext.value);
}

render(){
   return(
      <div>
         <Input ref={input => this.inputtext = input;} placeholder='message'/>
         <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
}

I need to take the inputs from the click event of the button. I can't figure out what's wrong. How can i get the input value properly?

3 Answers 3

9

In your case, you can also get the input value through this code:

this.inputtext.inputRef.value
Sign up to request clarification or add additional context in comments.

1 Comment

Yep this is what I do as well.
6

Since you have used the arrow operator, this.inputtext.value won't work, you need to write:

sendMessage(){
  console.log(this.inputtext.value);
}

In this case semantic-ui's Input Component is a div wrapped on top of input. So you cannot access input element directly through ref. You should use the react's preferred way to get the value, which is

<Input onChange={this.handleMessage.bind(this)} placeholder='message'/>


handleMessage (e) { console.log(e.target.value); }

or without using bind, babel-preset-stage-2 is required for this.

<Input onChange={this.handleMessage} placeholder='message'/>


handleMessage = e => { console.log(e.target.value); }

Comments

1

You need to use a normal class method for this to work. You also shouldn't have a semi-colon in the ref.

sendMessage() {
    console.log(this.inputtext.value);
  }

  render(){
     return(
       <div>
        <Input ref={input => this.inputtext = input} placeholder='message'/>
        <Button onClick={this.sendMessage}>Send</Button>
      </div>
   );
  }

2 Comments

im still getting it as undefined
As @Vikramaditya said it is due to Input not passing the ref prop to the input tag it generates. Try just using a plain input tag.

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.