DCR
DCR

Reputation: 15665

what's the advantage of using ref versus id when referencing the input value

what's the advantage of using:

this.refs.id.value

versus using:

document.getElementById('newID').value

is it just shorter syntax or is something else going on?

Upvotes: 7

Views: 6506

Answers (2)

kmjb
kmjb

Reputation: 170

Refs can work like HTML IDs however you do not suffer the re-usability problem. In HTML once you set ID of an element. You cannot re use your component again for the element you are trying to get by ID is totally unique. Refs allow you to specify a reference instead of an ID, this reference allows you to well, reference the current element being referred to. Using IDs the browser will only ever get the first in the series of qualified nodes. Take the following example:

class YourComponent extends React.Component {
    onBlur() {
        this.refs.referenceValue.setAttribute('class', '');
    }
    render() {
        return (
            <div>
                <input ref="referenceValue" onBlur={this.onBlur.bind(this)}/>
            </div>
        );
    }
}

This way, you can have multiple components with the same reference If you were to attempt to achieve this using IDs you will come to obstacles quite soon!

Upvotes: 3

Chen-Tai
Chen-Tai

Reputation: 3473

The benefit is using ref has good reusability and scope. Because ref only stay in this component, when you manipulate this ref, it won't interfere other component.

If you use id, it has duplicate problem. Think about this component.

class Demo extends React.Component {
  componentDidMount() {
    document.getElementById('demo').style.color = this.props.color;
  }

  render() {
    return (
      <div id="demo">
        content
      </div>
    );
  }
}

class Main exntends React.Component {
  render() {
    return (
      <div>
        <Demo color="red"/>
        <Demo color="green"/>
        <Demo color="blue"/>
      </div>
    )
  }
}

If use id to change the style property, all the <Demo/> text color will become blue(the last declaration).

But if you use ref, you can promise the manipulation keeps in this component.


I also find there is a similar question:

What is the difference with using ref and document.findElementById, ect when using ReactJS?

Upvotes: 11

Related Questions