Skip to content

Is there a way to access the DOM on Fresh? #2737

Answered by rschristian
rempas asked this question in Q&A
Discussion options

You must be logged in to vote

This doesn't have much to do with VDOM or JSX, just how components are built in (p)react.

Depends a bit on whether your click target is a component or not, but here's a super simple example of a toggle button component matching that doc:

function toggleDataTheme() {
    const theme = document.documentElement.getAttribute('data-theme');
    document.documentElement.setAttribute('data-theme', theme === 'dark' ? 'light' : 'dark');
}

function MyToggleButton() {
    return <button onClick={toggleDataTheme}>My Toggle Button</button>;
}

You can use bog-standard DOM queries in components, but it's important to know that islands, when server-side rendered, don't have access to the DOM. document w…

Replies: 1 comment 9 replies

Comment options

You must be logged in to vote
9 replies
@rempas
Comment options

@predaytor
Comment options

@rempas
Comment options

@rschristian
Comment options

Answer selected by rempas
@rempas
Comment options

@rschristian
Comment options

@rempas
Comment options

@rschristian
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants