Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

How do I select certain bars in react.js?

This is my code:

var Progressbar = React.createClass({     getInitialState: function () {         return { completed: this.props.completed };     },     addPrecent: function (value) {         this.props.completed += value;         this.setState({ completed: this.props.completed });     },      render: function () {          var completed = this.props.completed;         if (completed < 0) { completed = 0 };           return (...);     } 

I want to use this React component:

var App = React.createClass({     getInitialState: function () {          return { baction: 'Progress1' };     },     handleChange: function (e) {         var value = e.target.value;         console.log(value);         this.setState({ baction: value });     },     handleClick10: function (e) {         console.log('You clicked: ', this.state.baction);         document.getElementById(this.state.baction).addPrecent(10);     },     render: function () {         return (             <div class="center">Progress Bars Demo             <Progressbar completed={25} id="Progress1" />                 <h2 class="center"></h2>                 <Progressbar completed={50} id="Progress2" />                 <h2 class="center"></h2>                 <Progressbar completed={75} id="Progress3" />                 <h2 class="center"></h2>                 <span>                     <select name='selectbar' id='selectbar' value={this.state.baction} onChange={this.handleChange}>                         <option value="Progress1">#Progress1</option>                         <option value="Progress2">#Progress2</option>                         <option value="Progress3">#Progress3</option>                     </select>                     <input type="button" onClick={this.handleClick10} value="+10" />                     <button>+25</button>                     <button>-10</button>                     <button>-25</button>                 </span>             </div>         )     } }); 

I want to execute the handleClick10 function and perform the operation for my selected progressbar. But the result I get is:

 You clicked:  Progress1  TypeError: document.getElementById(...) is null 

How do I select the certain Element in react.js?

like image 659
user504909 Avatar asked Jun 29 '16 08:06

user504909


People also ask

How do you access the DOM element in React?

In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.

How do you get document getElementById in React?

getElementById in React is refs. We can assign a ref to an element and then retrieve the element that's assigned the ref from the ref's current property. to create a ref with the useRef hook and assign it to myContainer . Then we assign the ref to the div by setting the ref prop of the div to myContainer .

How do you access the DOM element in a React functional component?

Accessing DOM nodes in the same React component. To create a reference to a DOM node in a component we can do it either using the useRef() hook, which for most cases is the easier and best approach, or using the callback ref pattern which gives you more control when refs are set and unset.

Is getElementById a DOM method?

The getElementById() is a DOM method used to return the element that has the ID attribute with the specified value. This is one of the most common methods in the HTML DOM and is used almost every time we want to manipulate an element on our document.


2 Answers

You can do that by specifying the ref

EDIT: In react v16.8.0 with function component, you can define a ref with useRef. Note that when you specify a ref on a function component, you need to use React.forwardRef on it to forward the ref to the DOM element of use useImperativeHandle to to expose certain functions from within the function component

Ex:

const Child1 = React.forwardRef((props, ref) => {     return <div ref={ref}>Child1</div>  });  const Child2 = React.forwardRef((props, ref) => {     const handleClick= () =>{};     useImperativeHandle(ref,() => ({        handleClick     }))     return <div>Child2</div>  }); const App = () => {     const child1 = useRef(null);     const child2 = useRef(null);      return (         <>            <Child1 ref={child1} />            <Child1 ref={child1} />         </>     ) } 

EDIT:

In React 16.3+, use React.createRef() to create your ref:

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

In order to access the element, use:

const node = this.myRef.current; 

DOC for using React.createRef()


EDIT

However facebook advises against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases.

From the docs:

Legacy API: String Refs

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

A recommended way for React 16.2 and earlier is to use the callback pattern:

<Progressbar completed={25} id="Progress1" ref={(input) => {this.Progress[0] = input }}/>  <h2 class="center"></h2>  <Progressbar completed={50} id="Progress2" ref={(input) => {this.Progress[1] = input }}/>    <h2 class="center"></h2>  <Progressbar completed={75} id="Progress3" ref={(input) => {this.Progress[2] = input }}/> 

DOC for using callback


Even older versions of react defined refs using string like below

<Progressbar completed={25} id="Progress1" ref="Progress1"/>      <h2 class="center"></h2>      <Progressbar completed={50} id="Progress2" ref="Progress2"/>        <h2 class="center"></h2>      <Progressbar completed={75} id="Progress3" ref="Progress3"/> 

In order to get the element just do

var object = this.refs.Progress1; 

Remember to use this inside an arrow function block like:

print = () => {   var object = this.refs.Progress1;   } 

and so on...

like image 112
Shubham Khatri Avatar answered Sep 22 '22 18:09

Shubham Khatri


For getting the element in react you need to use ref and inside the function you can use the ReactDOM.findDOMNode method.

But what I like to do more is to call the ref right inside the event

<input type="text" ref={ref => this.myTextInput = ref} /> 

This is some good link to help you figure out.

like image 33
EQuimper Avatar answered Sep 19 '22 18:09

EQuimper