How to take inputs from <Input/> in react semantic UI

15,313

Solution 1

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); }

Solution 2

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

this.inputtext.inputRef.value

Solution 3

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>
   );
  }
Share:
15,313
Madushika Perera
Author by

Madushika Perera

Updated on June 08, 2022

Comments

  • Madushika Perera
    Madushika Perera almost 2 years

    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?

  • Madushika Perera
    Madushika Perera about 7 years
    im still getting it as undefined
  • spirift
    spirift about 7 years
    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.
  • Michael Ceber
    Michael Ceber about 5 years
    Yep this is what I do as well.