Use React ref to Get a Reference to Specific Components

InstructorJoe Maddalone

Share this video with your friends

Send Tweet

When you are using React components you need to be able to access specific references to individual component instances. This is done by defining a ref. This lesson will introduce us to some of the nuances when using ref.

Roman Liutikov
~ 10 years ago

In your example each state has initial value of 0, but each slider initial value is 128 (since min=0, max=255 and the thumb is in the middle of the slider).

What is the way to initialize these in sync when using refs? Maybe there's a better approach?

Roman Liutikov
~ 10 years ago

Ok, "Mixins" section already answered the question.

Pass initial value as a prop and use it with defaultValue prop.

Joel
~ 10 years ago

Are we dipping into the DOM 3x each time a single slider is adjusted? If so, any best practice advice for only querying the DOM element (slider) being adjusted? I can get it to work by binding this and the color to each Slider component, but it seems hacky: Slider ref="red" update={this.update.bind(this, "red")}

Chris
~ 9 years ago

I do not see the value in doing .getDOMNode vs, inp.getDOMNode.

León
~ 9 years ago

Am I the only one who see jQuery in this? I mean, "ref" depends on the structure of the HTML. If you change the hierarchy in the view it will fail

Joe Maddaloneinstructor
~ 9 years ago

@León - it's not HTML, it's JSX which represents JS functions.

<Slider ref="red" update={this.update} />

is translated to:

React.createElement(Slider, { ref: "red", update: this.update })

Intellective Learning
~ 9 years ago

this stackoverflow answer says to avoid refs. Also the documentation sounds like refs are not ideal. Can this be built easily without using refs? Should refs actually be avoided? Why or why not?

Joe
~ 9 years ago

I think this video is out of date and the finished code is different than the code that is below, which took me some time to realize.

Inside the slider class you want to make sure the input element has a ref called "inp". Like this:

class Slider extends React.Component { render() { return ( <div> <input type="range" ref="inp" onChange={this.props.update} min="0" max="255" /> </div> ); } }

The App itself needs to pull the value like this:

ReactDOM.findDOMNode(this.refs.red.refs.inp).value

The whole update method looks like this:

update(e) { this.setState({ red: ReactDOM.findDOMNode(this.refs.red.refs.inp).value, green: ReactDOM.findDOMNode(this.refs.green.refs.inp).value, blue: ReactDOM.findDOMNode(this.refs.blue.refs.inp).value }); }

~ 9 years ago

Is anyone else getting this error in the update method? Uncaught ReferenceError: ReactDOM is not defined

I dont seem to be getting this though when calling ReactDOM.render at the bottom of App.js