Search code examples
javascriptreactjsreact-dom

React interract with dom


How can I 'talk' with dom elements with react?

For example - I need to bind some actions with some js lib

Both approaches returns undefined for some reason

componentDidMount() {

    const element1 = document.querySelector('.home-container')
    const element2 = ReactDOM.findDOMNode(this);

     // returns undefined, undefined
    console.log(element1.length, element2.length); 

}

render() {

    return (
        <div className="home-container">
            ...
        </div>
    )
}

But console.log(element1) returns html from render itself though

How can I work with them? And what correct lifecycle method for this?


Solution

  • You use "refs":

    <div ref={e => {this.div = el}} ...>...</div>
    

    Once your component has rendered, with the above, its div property (you can use any name you want) will refer to the div element that was rendered.

    Here's an example largely copied from the link above that focuses a text input when it's rendered:

    class AutoFocusTextInput extends React.Component {
      componentDidMount() {
        this.textInput.focus();
      }
    
      render() {
        return (
          <input type="text"
            ref={(input) => { this.textInput = input; }} />
        );
      }
    }
    
    ReactDOM.render(
      <AutoFocusTextInput />,
      document.getElementById("root")
    );
    <div id="root"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>