How to Build an Accordion Tree in Preact Using the React TreeView Component? | Syncfusion Blogs
Detailed Blog page Skeleton loader
How to Build an Accordion Tree in Preact Using the React TreeView Component?

TL;DR: Build an accordion tree using the React TreeView in a Preact app, a lightweight React alternative. Set up a Preact app, integrate React components, and customize the TreeView for a sleek, functional UI. Perfect for enhancing Preact projects with powerful navigation!

Preact is a lightweight JavaScript library akin to React, emphasizing speed and minimalism with a core size of around 3KB. It maintains compatibility with React, allowing easy migration of codebases while offering optimized performance through an efficient virtual DOM implementation. Preact’s component-based architecture and support for hooks facilitate building reusable and modular UIs, making it a compelling choice for projects prioritizing speed and efficiency.

In this blog, we’ll build an accordion tree by integrating the Syncfusion React TreeView component in a Preact app.

Prerequisites

Before getting started with the app, ensure the following requirements for Preact and Syncfusion React components:

Setting up a Preact app with Vite

First, let’s create a new Preact app using Vite. Execute the following command to start the setup process.

npm init preact

Upon executing this command, you’ll be prompted with several queries, like below:

T  Preact - Fast 3kB alternative to React with the same modern API
|
o  Project directory:
|  my-app
|
o  Project Type:
|  Single Page Application (only client-side)
|
o  Project language:
|  TypeScript
|
o  Use router?
|  No
|
o  Use ESLint?
|  No
|
-

This will allow you to configure it based on your requirements.

Adding Syncfusion React packages

Syncfusion React components are available at npmjs.com. Install the Syncfusion React packages using the following command.

npm install --save @syncfusion/ej2-react-navigations

Building the accordion tree in the Preact app

Follow these steps to build an accordion tree using the Syncfusion React TreeView component in the Preact app: 

Step 1: Create the data source

First, create a JSON file at the path ~/src/datasource.json and add the data content for the TreeView component.

{
   "continents": [
      {
         "code": "AF",
         "name": "Africa",
         "countries": [
            { "code": "NGA", "name": "Nigeria" },
            { "code": "EGY", "name": "Egypt" },
            { "code": "ZAF", "name": "South Africa" }
         ]
      },
      {
         "code": "AS",
         "name": "Asia",
         "countries": [
            { "code": "CHN", "name": "China" },
            { "code": "IND", "name": "India", "selected": true },
            { "code": "JPN", "name": "Japan" }
         ]
      },
      {
         "code": "EU",
         "name": "Europe",
         "countries": [
            { "code": "DNK", "name": "Denmark" },
            { "code": "FIN", "name": "Finland" },
            { "code": "AUT", "name": "Austria" }
         ]
      },
      {
         "code": "NA",
         "name": "North America",
         "countries": [
            { "code": "USA", "name": "United States of America" },
            { "code": "CUB", "name": "Cuba" },
            { "code": "MEX", "name": "Mexico" }
         ]
      },
      {
         "code": "OC",
         "name": "Oceania",
         "countries": [
            { "code": "AUS", "name": "Australia" },
            { "code": "NZL", "name": "New Zealand" },
            { "code": "WSM", "name": "Samoa" }
         ]
      }
   ]
}

Step 2: Define the React TreeView component

In the ~/src/index.tsx file, define the React TreeView component along with the fields and events within the App component.

import { useRef } from 'preact/hooks';
import { TreeViewComponent } from '@syncfusion/ej2-react-navigations';
import { continents } from './datasource.json';

function App() {
    // Data source for TreeView component
    let field = {
        dataSource: continents,
        id: "code",
        text: "name",
        child: "countries"
    };
    let style = 'accordiontree';
    let treeObj = useRef<TreeViewComponent | null>(null);

    function nodeSelect(args) {
        if (args.node.classList.contains('e-level-1')) {
            treeObj.current.collapseAll();
            treeObj.current.expandAll([args.node]);
            treeObj.current.expandOn = 'None';
        }
    }
return (
<div className='control-pane'> <div className='control-section'> <div id='treeparent'> <TreeViewComponent fields={field} cssClass={style} ref={treeObj} nodeSelected={nodeSelect.bind(this)}/> </div> </div> </div>); } export default App;

Step 3: Apply custom styling

To create an accordion tree in Preact app, we need to customize the app by styling the TreeView component with custom styles in the ~/src/style.css file.

@import '@syncfusion/ej2-base/styles/material3.css';
@import '@syncfusion/ej2-buttons/styles/material3.css';
@import '@syncfusion/ej2-inputs/styles/material3.css';
@import '@syncfusion/ej2-popups/styles/material3.css';
@import '@syncfusion/ej2-react-navigations/styles/material3.css';

#treeparent {
    display: block;
    max-width: 350px;
    max-height: 350px;
    margin: auto;
    overflow: auto;
}

#treeparent .e-list-item.e-level-1 > .e-fullrow {
    background-color: darkslateblue;
    border-color: darkslateblue;
}

#treeparent .e-list-item.e-level-1 > .e-text-content .e-list-text {
    color: white;
    font-size: 16px;
}

#treeparent .e-list-item.e-level-1 .e-icons {
    display: none;
}

#treeparent .e-list-item.e-level-2 > .e-fullrow {
    background-color: white;
    border-color: white;
}

#treeparent .e-list-item.e-level-2 > .e-text-content .e-list-text {
    color: blue;
    font-size: 14px;
}

Here is the summarized code for the above steps in the ~/src/index.tsx file.

import { render } from 'preact';
import { useRef } from 'preact/hooks';
import { TreeViewComponent } from '@syncfusion/ej2-react-navigations';
import { continents } from './datasource.json';
import './style.css';

function App() {
    // Data source for TreeView component
    let field = { dataSource: continents, id: "code", text: "name", child: "countries" };
    let style = 'accordiontree';
    let treeObj = useRef(null);

    function nodeSelect(args) {
        if (args.node.classList.contains('e-level-1')) {
            treeObj.current.collapseAll();
            treeObj.current.expandAll([args.node]);
            treeObj.current.expandOn = 'None';
        }
    }
return (
<div className='control-pane'> <div className='control-section'> <div id='treeparent'> <TreeViewComponent fields={field} cssClass={style} ref={treeObj} nodeSelected={nodeSelect.bind(this)}/> </div> </div> </div>); } export default App; render(<App />, document.getElementById('app'));

Run the project

Finally, run the project using the following command.

npm run dev

Then, navigate to http://127.0.0.1:5173/ in your preferred browser to see the rendered React TreeView component within the Preact project.

The output should look like the following image.

Building an Accordion tree using React TreeView Component
Building an accordion tree using the React TreeView component in the Preact app

Explore the endless possibilities with Syncfusion’s outstanding React UI components.

Conclusion

Thanks for reading this blog! We’ve seen how to build an accordion tree using Syncfusion React TreeView in a Preact app. Try out the steps provided in this blog, and leave your feedback in the comments below!

The new version of Essential Studio® is available for existing customers on the License and Downloads page. If you are not a Syncfusion customer, try our 30-day free trial to check out our available features.

For questions, you can also contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Be the first to get updates

Piramanayagam Ramakrishnan

Meet the Author

Piramanayagam Ramakrishnan

Piramanayagam is a Product Manager at Syncfusion. He has 6+ years of experience in web product development. He helps people using Syncfusion controls in their applications.