Getting Started with Preact: Shallow Rendering and DOM Manipulation
Written on
Chapter 1: Introduction to Preact
Preact is a lightweight front-end framework that bears resemblance to React but is designed to be simpler and more efficient. This article will guide you through the basics of front-end development using Preact.
Section 1.1: Understanding Shallow Rendering
Shallow rendering allows you to render a single level of a component without delving into its child components. For instance, the following code demonstrates shallow rendering:
import { shallowRender } from "preact-render-to-string";
import { h } from "preact";
const Foo = () => <div>foo</div>;
const App = <div><Foo /></div>;
console.log(shallowRender(App));
The output will be an empty string since the Foo component is not rendered.
Section 1.2: Pretty Print for Enhanced Readability
We can present the rendered output in a more readable format using the pretty option. This can be achieved with the following code:
import { render } from "preact-render-to-string";
import { h } from "preact";
const Foo = () => <div>foo</div>;
const App = <div><Foo /></div>;
console.log(render(App, {}, { pretty: true }));
The result will display:
<div>
foo</div>
Section 1.3: JSX Rendering Mode for Testing
The JSX rendering mode is particularly useful for snapshot testing, as it formats the output to resemble JSX syntax. The following example illustrates this:
import render from "preact-render-to-string/jsx";
import { h } from "preact";
const App = <div>Hello, Preact!</div>;
console.log(render(App));
The output will appear as:
<div>Hello, Preact!</div>
Chapter 2: External DOM Manipulations
To incorporate external DOM mutations within your Preact components, you need to disable the virtual DOM's rendering and diffing algorithm to prevent it from reversing these changes. An example is provided below:
import { Component, render } from "preact";
class Example extends Component {
shouldComponentUpdate() {
return false;}
componentDidMount() {
let thing = document.createElement("maybe-a-custom-element");
this.base.appendChild(thing);
}
render() {
return <div>Example Component</div>;}
}
const App = () => <Example />;
if (typeof window !== "undefined") {
render(<App />, document.getElementById("root"));}
By returning false in shouldComponentUpdate, we effectively stop the virtual DOM diffing process. During componentDidMount, we can manipulate the DOM directly by creating and appending new elements.
Conclusion
In summary, Preact allows for shallow rendering and pretty printing of components, as well as direct manipulation of the DOM within your components, making it a powerful tool for web development.