Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="https://cdn.jsdelivr.net/npm/gun/gun.js"></script>

<div id="root"></div>
              
            
!

CSS

              
                body {
  height: 100vh;
  display: grid;
  place-items: center;
}

.box {
  width: 300px;
  
  h1 {
    font-size: 20px;
  }
}

p {
  margin-bottom: 1em;
}

              
            
!

JS

              
                // https://siriusbusiness.fi/gun-for-react-state-management
import React, { useState, useEffect, useRef } from "https://cdn.skypack.dev/react";
import ReactDOM from "https://cdn.skypack.dev/react-dom";

const GunContext = React.createContext({});
GunContext.displayName = 'GunContext';

const GunProvider = ({ initialState, ...props }) => {
  // Initialize Gun with options that make sure the state is synced to localStorage only
  const gun = new Gun({
    localStorage: true,
    file: 'State.local', 
    multicast: false,
    peers: []
  }).get('state');
  
  const State = useRef(gun);
  const subscriptions = useRef({});
  const [state, setState] = useState(initialState);
  
  const callback = (values, key, _, subscription) => {
    delete values['_'];
    if (subscriptions.current[key] && subscriptions.current[key] !== subscription){
      // Dunno if this can actually happen at Gun level but just making sure if the same key has
      // two different subscriptions we remove the old one. I've never seen this happen, tho
      subscriptions.current[key].off();
    }
    subscriptions.current[key] = subscription;
    setState((oldState)=> ({...oldState, ...values }));
  }
  
  const put = (key, value) => State.current.get(key).put(value);
  
  useEffect(() => {
    State.current.on(callback);
    
    return () => {
      Object.keys(subscriptions.current).forEach(k => {
        const subscription = subscriptions[k];
        subscription && subscription.off();
        delete subscriptions[k];
      });
    }
  }, []);

  const value = React.useMemo(() => [state, put], [state, put]);

  return <GunContext.Provider value={value} {...props} />;
};

function useGunState() {
  const context = React.useContext(GunContext);
  if (context === undefined) {
    throw new Error(`useGunState must be used within a GunProvider`);
  }
  return context;
}

const TextInput = () => {
  const [state, setState] = useGunState();

  const onInput = (e) => setState('text', e.target.value)

  return (
    <form class="box">
      <input placeholder="Type something" type="text" value={state?.text} onChange={onInput} />
    </form>
  );
}

const TextInputList = () => {
  const [state, setState] = useGunState();
  
  return (
    <>
      <p>
        <button onClick={() => setState('elementCount', Math.max(state?.elementCount - 1, 0))}>Remove element</button>
        <button onClick={() => setState('elementCount', state?.elementCount + 1)}>Add element</button>
      </p>
      {[...Array(state.elementCount)].map((e, i) => <TextInput key={i} />)}
   </>
  );
}

const el = document.querySelector("#root");
ReactDOM.render(
  <GunProvider initialState={{ elementCount: 2, text: '' }}>
    <p class="box">The input value is synced across component instances and persisted in localStorage. State changes are properly unsubscribed on unmount.</p>
    <TextInputList />
  </GunProvider>, el);
              
            
!
999px

Console