How to find element by Key in React?

If you want to get access to the DOM node of a React element, use the ref prop.
But in most cases, you can achieve what you're looking for without using Refs, so make sure you are not abusing this feature.

Here is some information from React docs: Refs and the DOM - React

Refs and the DOM

Refs provide a way to access DOM nodes or React elements created in the render method.

When to Use Refs

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

Avoid using refs for anything that can be done declaratively.

Creating Refs

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }
  render() {
    return <div ref={this.myRef} />;
  }
}

Accessing Refs

const node = this.myRef.current;

Access to key has been removed in React.

The props key and ref were already reserved property names.
...
You can no longer access this.props.ref and this.props.key from inside the Component instance itself. https://facebook.github.io/react/blog/2014/10/16/react-v0.12-rc1.html#breaking-change-key-and-ref-removed-from-this.props

You can simply use a different name (e.g. 'reactKey') and access it via props. Here is a demo: http://codepen.io/PiotrBerebecki/pen/PGaxdx

class App extends React.Component {
  render() {
    return (
      <div>
        <Child key="testKey1" keyProp="testKey1"/>
        <Child key="testKey2" keyProp="testKey2"/>
        <Child key="testKey3" keyProp="testKey3"/>
        <Child key="testKey4" keyProp="testKey4"/>
      </div>
    );
  }
}

class Child extends React.Component {
  render() {
    console.log(this.props);  // only 'keyProp' is available

    let getClassName = () => {
      switch (this.props.keyProp) {
        case 'testKey1': 
          return 'red';
        case 'testKey2': 
          return 'green';
        case 'testKey3': 
          return 'blue';
        default: 
          return 'black';
       }
    };

    return (
      <div className={getClassName()}>
        Some Text
      </div>
    );
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

Tags:

Reactjs