Search code examples
javascriptreactjsmaterialize

Run decorative function to DOM node in react after rendering


I am currently using MaterializeCSS in my project. Some component in the library requires calling some functions to decorate a node after rendering. For instance, I need to run

var instance = M.FormSelect.init(elem, options);

after the <select> node is rendered so it is decorated. However, how do I do that properly in react? My current hack is to do a document.querySelector (by assigning a unique ID to the component because react doesn't store the rendered node reference, unless... i use react-dom?), and run the initialization in componentDidMount(). While it works, but it just doesn't feel like the proper way of getting things done.


Solution

  • You can use refs for this, as described in the documentation. It states that refs are good for when you need to do imperative animations, which I believe suits your use case.

    As the docs explain, the ref attribute takes a callback, and when used on an html element, the first arg of the callback is the underlying DOM node.

    <div ref={(node) => { /* perform imperative operations */ }}></div>