Preact is a fast, lightweight, and efficient JavaScript library for building user interfaces. It provides a simplified API for building web components and is designed to be used as a drop-in replacement for React. In this tutorial, you will learn the basics of Preact and how to get started building web components with it.
Step 1: Installing Preact
The first step to get started with Preact is to install it in your project. You can install Preact via npm by running the following command:
Copy codenpm install preact
Step 2: Creating a Preact Component
Preact components are JavaScript functions or classes that return a virtual tree of HTML elements. Here is an example of a simple Preact component:
javascriptCopy codeimport { h, render } from "preact";
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
render(<Welcome name="Preact" />, document.body);
Step 3: Adding Props and State
Preact components can have properties (props) and state. Props are data that is passed to the component from its parent component. State is data that is internal to the component and can be updated over time.
Here is an example of a Preact component that has both props and state:
javascriptCopy codeimport { h, render, useState } from "preact";
function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
}
render(<Counter initialCount={0} />, document.body);
Step 4: Rendering Components
Finally, you can render your Preact components to the DOM using the render
function. The first argument to render
is the component to render, and the second argument is the DOM node to render it into.
Here is an example of rendering a component to the body
of the document:
javascriptCopy codeimport { h, render } from "preact";
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
render(<Welcome name="Preact" />, document.body);
In conclusion, Preact is a simple and efficient library for building web components. By following these basic steps, you can get started building your own Preact components today!