1

For accessing React element or component, 'ref' is the best possible method? Do we have any other options for the same in ReactJS

<TextField
    ref={(elem) => this.textField = elem}
    value={value}
    {...restProps}
/>
2
  • What exactly are you planning to do with textField? Commented Mar 29, 2017 at 21:14
  • I just want to read the input value from Stateless TextField component Commented Apr 5, 2017 at 3:05

1 Answer 1

1

If you want to access the actual DOM node, then ref is the only option. Generally refs are used to create uncontrolled components, where we let the DOM keep charge of the input's value, and get the value from our reference to the DOM node when we need it. You can't use value as a prop on these components, but you can use defaultValue to set their initial value:

class WithUncontrolledTextInput extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.textField.value}`);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref={input => this.textField = input} defaultValue='hello' />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}

The alternative approach is to use a controlled component, where the current value of the input is stored within the component's state, and updated whenever the input value is updated.

class WithControlledTextInput extends React.Component {
  constructor() {
    super();
    this.state = {
      textField: 'hello'
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    console.log(`The input value is ${this.state.textField}`);
  }

  handleInput(e) {
    this.setState({
      textField: e.target.value
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input value={this.state.textField} onChange={this.handleInput} />
        <input type='submit' value='Submit' />
      </form>
    );
  }
}
Sign up to request clarification or add additional context in comments.

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.