7

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?

1

2 Answers 2

11

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?

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

1 Comment

This didn't make much sense to me, changing the id selector to ref.current.style.color = this.props.color; would still change all children colouring, I don't see the difference.
3

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!

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.