1

I have an input field that the user types into. This Input field looks like this:

// within React component render function:
...
        <input
          id="autoComplete"
          className={inputClasses}
          type="text"
          // used to display user typed words in input field
          ref={this.inputRef}
          // onchange is used to store value in redux store
          onChange={this.inputChangeHandler}
        />

In the above code, the 'ref' is for displaying the user typed letter in the input field. However, I also have Google Maps Autocomplete integrated into this input field. The Autocomplete feature works fine & when the user clicks on one of the autocomplete results, the input field is populated by that name & onChange handler stores the value within the redux store.

So far, so good. However, now, when the user navigates to another section of the site, how do I populate the input field with the value within the redux store. There is no 'value' attribute on the input field, & its using React's ref method.

Thank you

0

1 Answer 1

1

You can change/add value to input element using ref. ref will basically have the reference of actual dom node, so by changing this.refName.current.value will change the input value.

But you need to do it after initial rending, means after ref get the reference of input element.

Check this working example:

class App extends React.Component {

  constructor() {
    super();
    this.a = React.createRef();
  }
  
  click = () => {
    this.a.current.value = Math.floor(Math.random()*100);
  }
  
  render() {
    return (
      <div>
        <input ref={this.a} placeholder="Number" />
        <button onClick={this.click}>Click here to change the input value</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id='app' />

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

1 Comment

Thank you Mayank, this was great help. I ended up using callback ref as it gives a bit more finer control. Thank you for the guidance.

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.