46

Not able to get values of input type using this.refs... how to get that values from input type

   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }

10 Answers 10

29

You should avoid ref="googleInput" as it is now considered legacy. You should instead declare

ref={(googleInput) => { this.googleInput = googleInput }}

Inside of your handler, you can use this.googleInput to reference the element.

Then inside of your submitForm function, you can obtain the text value with this.googleInput._getText()

String refs are legacy https://facebook.github.io/react/docs/refs-and-the-dom.html

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

Edit

From React 16.3, the format for creating refs are:

class Component extends React.Component 
{
        constructor() 
        {
            this.googleInput = React.createRef();
        }

        render() 
        {
            return 
            (
                <div ref={this.googleInput}>
                    {/* Details */}
                </div>
            );
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

@ShubhamKhatri Please consider downvoting if you feel this answer does not contribute to the question. The OP asked how to use ref to obtain the value of an input field, this answer provides a solution to help satisfy that.
This doesn't work. I'm getting an error saying Uncaught TypeError: _this.googleInput._getText is not a function
Minus 1 for still using _getText(). It should be this.googleInput.current.value
18

using ref={ inputRef => this.input = inputRef } is considered legacy now. In React 16.3 onwards, you can use the code below,

class MyForm extends React.Component {
    constructor(props) {
        //...
        this.input = React.createRef();
    }

    handleSubmit(event) {
        alert('A name was submitted: ' + this.input.current.value);
        event.preventDefault();
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name:
                    <input type="text" ref={this.input} />
                </label>
                <input type="submit" value="Submit" />
            </form>
        );
    }
}

EDIT: thanks for the comment @stormwild

2 Comments

React.createRef was introduced in React 16.3. If you're using an earlier version of React callback refs is recommended. reactjs.org/docs/refs-and-the-dom.html
how can we set the value of input tags using refs?
14

In case any one is wondering how to implement ref with hooks :

// Import
import React, { useRef } from 'react';


const Component = () => {
    // Create Refs
    const exampleInput = useRef();

    const handleSubmit = (e) => {
        e.preventDefault();
   
         const inputTest = exampleInput.current.value;

     }

    return(
        <form onSubmit={handleSubmit}>
            <label>
                Name:
                <input type="text" ref={exampleInput} />
            </label>
            <input type="submit" value="Submit" />
        </form>
}

Comments

8
getValue: function() {
    return this.refs.googleInput.value;
  }

Comments

6

I think the more idiomatic way is to use state instead of refs, although it's a little more code in this case since you only have a single input.

export class BusinessDetailsForm extends Component {

  constructor(props) {
    super(props);
    this.state = { googleInput: '' };
    this.defaultValue = 'someValue';
    this.handleChange = this.handleChange.bind(this);
    this.submitForm = this.submitForm.bind(this);
  }

  handleChange(e) {
    const { field, value } = e.target;
    this.setState({ [field]: value });
  }
  submitForm() {
    console.log(this.state.googleInput);
  }
  render() {
    return (
      <Formsy.Form onSubmit={this.submitForm} id="form_validation">
        <Field type="text"
          name="googleInput"
          onChange={this.handleChange}
          component={GoogleAutoComplete}
          floatingLabelText="location"
          hintText="location"
          id="addressSearchBoxField"
          defaultValue={this.defaultValue}
          onSelectPlace={this.handlePlaceChanged}
          validate={[ required ]}
        />
      </Formsy.Form>
    );
  }
}

See https://facebook.github.io/react/docs/forms.html#controlled-components.

3 Comments

I have always preferred the handleChange method you're using here. I know this is an old post, but in case someone sees this answer here is a slightly more "sugary" syntax handleChange = ({ target: { name, value } }) => this.setState({ [ name ]: value });
Keeping a text input's value in state can bring a whole list of re-rendering headaches for child components; using a ref avoids this and is fine practice.
@DaydreamNation I'm not sure what the headaches are. Per the React docs, "The standard way to achieve this is with a technique called “controlled components.”
2

Using RN 0.57.8 when tried this.googleInput._getText(), It resulted in error _getText is not a function so i printed this.googleInput in console and found that _getText() is a function inside _root

  1. this.googleInput._root._getText()
  2. this.googleInput._root._lastNativeText - This will return the last state not the current state please be careful while using it.

1 Comment

although, the exact _root._getText() didnt give me exact thing i was looking for. your thinking process to get related methods along with react extention in chrome helped me get the required method.
1

In 2018 you should write in constructor this: In constructor of class you should add something like this.input = React.createRef()

Examples here: https://reactjs.org/docs/uncontrolled-components.html

Comments

1

I tried the answer above (https://stackoverflow.com/a/52269988/1978448) and found it only worked for me when I put the refs in the state, but not when I just made them properties of the component.

Constructor:

this.state.refs={
  fieldName1: React.createRef(),
  fieldName2: React.createRef()
};

and in my handleSubmit I create a payload object to post to my server like this:

var payload = {
  fieldName1: this.state.refs.fieldName1.current.value,
  fieldName2: this.state.refs.fieldName2.current.value,
}

Comments

1

The react docu explains it very well: https://reactjs.org/docs/refs-and-the-dom.html

this is considered legacy:

yourHandleMethod() {
  this.googleInput.click();
};

yourRenderCode(){
  ref={(googleInput) => { this.googleInput = googleInput }}
};

whereas, this is considered the way to go:

constructor(props){
  this.googleInput = React.createRef();
};
yourHandleMethod() {
  this.googleInput.current.click();
};
yourRenderCode(){
  <yourHTMLElement
    ref={this.googleInput}
  />
};

Comments

1

From React 16.2, you can use: React.createRef

See more: https://reactjs.org/docs/refs-and-the-dom.html

1. using ref={ inputRef => this.input = inputRef }

Exam:

import React, { Component } from 'react';

class Search extends Component {
    constructor(props) {
        super(props);

        this.name = React.createRef();

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

    handleClick() {
        this.props.onSearch(`name=${this.name.value}`);
    }

    render() {
        return (
            <div>
                <input
                    className="form-control name"
                    ref={ n => this.name = n }
                    type="text"
                />

                <button className="btn btn-warning" onClick={ this.handleClick }>Search</button>
            </div>
        );
    }
}

export default Search;

ref={ n => this.name = n } Use Callback Refs -> see

Or:

2. this.name.current.focusTextInput()

    class Search extends Component {
        constructor(props) {
            super(props);

            this.name = React.createRef();

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

        handleClick() {
            this.props.onSearch(`name=${this.name.current.value}`);
        }

        render() {
            return (
                <div>
                    <input
                        className="form-control name"
                        ref={this.name}
                        type="text"
                    />

                    <button className="btn btn-warning" onClick={ this.handleClick }>Search</button>
                </div>
            );
        }
    }

    export default Search;

Hope it will help you.

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.