Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find element by Key in React?

Tags:

<ul>     <li key='search1'>1234</li>     <li key='search2'>5678</li>     <li key='search3'>9</li> </ul> 

How to find element by Key and change element values like addClass/innerHtml?

Note: In Plain React - No Flux or Jsx.

like image 454
Jayamurugan Avatar asked Oct 13 '16 12:10

Jayamurugan


People also ask

How do you access the element using the key in React?

How to find element by Key and change element values like addClass/innerHtml? Note: In Plain React - No Flux or Jsx. If you want to change a class or the content of an element, do not use addClass or innerHtml but make it work in the React way by dynamically adding classes and children/content in the render method.

Can I use getElementById in React?

getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .

How do I map a key value in React?

To map through an object's value in React:Use the Object. values() method to get an array of the object's values. Call the map() method on the array of values.

How do you find components in React?

Open the console by either right-clicking and inspecting an element or by opening the toolbar by clicking View > Developer > JavaScript console. The Components tab will show the current React component tree, along with any props, state, or context.


1 Answers

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') ); 
like image 182
Piotr Berebecki Avatar answered Sep 18 '22 09:09

Piotr Berebecki