How to create a component in Preact

Preact is a fast 3kB alternative to React, with the same modern API. It is a lightweight JavaScript library for building user interfaces. Preact is easy to use and provides a great way to create components for your web applications. In this tutorial, we will show you how to create a component in Preact.

Install Preact

The first step is to install Preact. You can do this using npm or yarn. To install Preact using npm, run the following command:

npm install preact

To install Preact using yarn, run the following command:

yarn add preact

Create a Component File

Once Preact is installed, you can create a component file. This file will contain the code for your component. Create a file called MyComponent.js in the same directory as your project.

Import Preact

Next, you need to import Preact into your component file. To do this, add the following line of code to the top of your component file:

import { h, Component } from 'preact';

This will import the h and Component functions from Preact.

Create the Component

Now you can create the component. To do this, add the following code to your component file:

class MyComponent extends Component { // ...}

This will create a class called MyComponent that extends the Component class from Preact.

Add a Render Method

Next, you need to add a render method to your component. This method will be called when the component is rendered. Add the following code to your component file:

render() { return ( <div> Hello World! </div> );}

This will render a <div> element with the text “Hello World!” when the component is rendered.

Export the Component

Finally, you need to export the component so that it can be used in other parts of your application. To do this, add the following line of code to the bottom of your component file:

export default MyComponent;

This will export the MyComponent class so that it can be used in other parts of your application.

Conclusion

In this tutorial, we have shown you how to create a component in Preact. We have covered how to install Preact, create a component file, import Preact, create the component, add a render method, and export the component. We hope you have found this tutorial helpful.

Useful Links