How do I control DOM elements with FreshJs

284 Views Asked by At

I am trying to learn the new Deno framework, FreshJS. The only thing troubling me right now is DOM control. If I wanted to dynamically update a menu item or change the color of a container how would I do so?

Essentially...how can I getElementByID() with FreshJS? I haven't found any documentation on how to do this.

I have tried the vanillaJS methods but those don't seem to work (I never thought they would) and I have looked up some ways of DOM control with preact but I really didn't find anything that seemed like it would work inside Fresh.

2

There are 2 best solutions below

0
On BEST ANSWER

Short answer: you don't.

The point of these JS UI frameworks (not just Preact) is to get away from direct DOM manipulation, for performance, DX, or maintainability reasons. Every framework has its own way to create and manage state as well as updating the UI when that state changes.

To change a color in a component in Fresh/Preact, you could do something like this:

// islands/MyComponent.tsx
import { useState } from 'preact/hooks';

export function MyComponent() {
    const [enabled, setEnabled] = useState(false);

    return (
        <div>
            <h1 style={{ color: enabled ? 'blue' : 'red' }}>Hello World!</h1>
            <button onClick={() => setEnabled(!enabled)}>Click me to toggle the colors</button>
        </div>
    );
}

We create a state value enabled and have a way to update it with setEnabled. When you click the button, it toggles this state value using the setter which will then cause the component to rerender. Any conditional logic in the template will be re-evalutated, causing the color to change.

Fresh is built upon Preact, so I highly recommend you go through Preact's tutorial which introduces concepts such as components, renders, and VDOM, as it seems you're unfamiliar with modern UI frameworks and how they work.

https://preactjs.com/tutorial/

1
On

There is some similarity with ReactJS maybe it has ReactJS at its core I don't know I'd never used it before, but I was seeking in its doc and I found this https://fresh.deno.dev/docs/getting-started/adding-interactivity Where they use some react hooks from preact/hooks, I believe there is useRef hook you should use.