Can you manipulate the DOM directly while using Preactjs?

Viewed 259

I am looking into Preact for my next project.

Since it has no virtual DOM I am wondering if it, like React, prefers you to let the framework manipulate the DOM instead of doing so yourself directly.

Would Preact bump heads with another library that manipulates the DOM such as SVGjs?

1 Answers

Preact is non-destructive when it comes to DOM updates. The official guide already explains how to integrate external DOM manipulations into the preact component:

If using class-based component:

import { h, Component } from 'preact';

class Example extends Component {

  shouldComponentUpdate() {
    // IMPORTANT: do not re-render via diff:
    return false;
  }

  componentWillReceiveProps(nextProps) {
    // you can do something with incoming props here if you need
  }

  componentDidMount() {
    // now mounted, can freely modify the DOM:
    const thing = document.createElement('maybe-a-custom-element');
    this.base.appendChild(thing);
  }

  componentWillUnmount() {
    // component is about to be removed from the DOM, perform any cleanup.
  }

  render() {
    return <div class="example" />;
  }
}

If using hooks, then use memo function from preact/compat:

import { h } from 'preact';
import { useEffect } from 'preact/hooks';
import { memo } from 'preact/compat';

function Example(props) {

  const [node, setNode] = setState(null);

  useEffect(() => {
    const elm = document.createElement('maybe-a-custom-element');

    setNode(elm);

    // Now do anything with the elm.
    // Append to body or <div class="example"></div>

  }, []);

  return <div class="example" />;
}

// Usage with default comparison function
const Memoed = memo(Example);

// Usage with custom comparison function
const Memoed2 = memo(Example, (prevProps, nextProps) => {
  // Only re-render when `name' changes
  return prevProps.name === nextProps.name;
});

Also, note that Preact's render() function always diffs DOM children inside of the container. So if your container contains DOM that was not rendered by Preact, Preact will try to diff it with the elements you pass it. - Thus the meaning non-destructive.

Related