Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React. Cannot get the component element in the DOM

I'm trying to insert the innerHTML for the div container ed. But I cannot get it after the React has render it. I understand that it's the problem with the stages of render, because I get null for this div container. What is I'm making the wrong?

class Test extends React.Component {
  render() {
    return (
      <div> 
        <div id='ed'>
        <p>{this.props.prop.text}</p>
        </div> 
        {document.querySelector('#ed').innerHTML = this.props.prop[1]} // this the problem
      </div> 
    );
  }
}

ReactDOM.render(
  <Test prop={store.getState()} />,
  document.getElementById('root')
);
like image 731
Max Wolfen Avatar asked Mar 10 '18 23:03

Max Wolfen


People also ask

How do I get the DOM element from the React component?

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 grab elements in React?

To get an element by ID in React: Set the ref prop on the element. Use the current property to access the element in the useEffect hook.

Is it okay to 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 .


1 Answers

Your direct DOM manipulation won't work cause you called it in render().

You called Query selector in render(), Query selector or findDOMNode() only works on mounted components (that is, components that have been placed in the DOM).

If you try to call this on a component that has not been mounted yet (like calling Query selector or findDOMNode() in render() on a component that has yet to be created) an exception will be thrown.

you can do expressions in render() usually, but you can't get access the DOM element in render() since it is placing your elements in render() to DOM.

Use lifeCycle methods instead and You can use ReactDOM.findDOMNode(this) to access the underlying DOM node. But accessing the DOM node and manipulating like you do is against the React style of programming.

Query selector shouldn't be necessary with react just attach a ref to the element you want and you have access to it within any function of the react component.

Example Demo : demo

like image 170
Jayavel Avatar answered Oct 11 '22 03:10

Jayavel