How to use preact - 10 common examples

To help you get started, we’ve selected a few preact examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github developit / preact-redux / test / provider.js View on Github external
import { createStore } from 'redux';
import { Provider, connect, connectAdvanced } from '../';
import { render, options } from 'preact';
import React from 'preact';

import * as Redux from '../dist/preact-redux.esm.js';

// disable async rendering entirely to make tests simpler
options.debounceRendering = f => f();

describe('preact-redux', () => {
	it('should export Provider & connect', () => {
		expect(Provider).to.be.a('function');
		expect(connect).to.be.a('function');
	});

	describe('', () => {
		it('should commit store prop to context', () => {
			let store = createStore( a => a );
			let Child = sinon.stub().returns(<div>);

			render((
				
					
				</div>
github mongodb / docs-tools / themes / mongodb / src / widgets / deluge / MainWidget.js View on Github external
import PropTypes from 'prop-types';
import preact from 'preact';

// State enum
const STATE_INITIAL = 'Initial';
const STATE_VOTED = 'Voted';

class MainWidget extends preact.Component {
    constructor(props) {
        super(props);
        this.state = {
            'state': STATE_INITIAL
        };

        this.onSubmit = this.onSubmit.bind(this);
        this.onInitialVote = this.onInitialVote.bind(this);
        this.onToggle = this.onToggle.bind(this);
    }

    onSubmit() {
        this.props.onSubmit(this.state.state);
        this.setState({'state': STATE_VOTED});
    }
github wearekuva / oui / es2015 / controls / textinput / textinput.js View on Github external
/** @jsx React.h */
import React from 'preact'
import PropTypes from 'proptypes'
// import radium from 'radium'
import { base, highlight, secondary } from '../styles'

/**

	A simple wrapper around a editable text field. It pretty much does what you'd
	expect it to.

*/

class TextInput extends React.Component {

  render () {
    const { value, label, onChange, style, pattern, onSubmit } = this.props
		const conditionOnChange = value =&gt; pattern.test(value) ? onChange(value) : null
		const conditionOnSubmit = value =&gt; pattern.test(value) ? onSubmit(value) : null

    return <div style="{{">
       <label>{label}</label>
       <input maxlength="6" style="{{" value="{value}" type="text"> conditionOnChange(evt.target.value)}
         onChange={evt =&gt; conditionOnSubmit(evt.target.value)} /&gt;
     </div>
  }
}

// TextInput = radium( TextInput )
github preactjs / preact-devtools / src / view / components / TreeView.tsx View on Github external
const onKeyDown = useKeyListNav({
		selected,
		onCollapse: collapseNode,
		canCollapse: id =&gt; {
			const node = store.nodes.$.get(id);
			return node ? node.children.length &gt; 0 : false;
		},
		checkCollapsed: id =&gt; collapsed.has(id),
		onNext: selectNext,
		onPrev: selectPrev,
	});

	const onMouseLeave = useCallback(() =&gt; store.actions.highlightNode(null), []);
	const ref = useRef(null);
	const paneRef = useRef(null);

	useEffect(() =&gt; {
		if (ref.current &amp;&amp; paneRef.current) {
			const available = ref.current.offsetWidth;
			const actual = paneRef.current.offsetWidth;
			const diff = actual - available;
			if (diff &gt; 0) {
				const current = cssToPx(
					getComputedStyle(ref.current).getPropertyValue("--indent-depth"),
				);

				const indent =
					current - Math.round((diff / (treeDepth || 1)) * 100) / 100;

				// Only change indentation when it's smaller
				console.log({ indent, current });
github GoogleChrome / lighthouse-ci / packages / server / src / ui / hooks / use-api-data.jsx View on Github external
function useApiData(apiMethod, apiParameters) {
  const [loadingState, setLoadingState] = useState(/** @type {LoadingState} */ ('loading'));
  const [apiData, setApiData] = useState(/** @type {any} */ (undefined));

  useEffect(() => {
    if (!apiParameters) return;

    // Wrap in IIFE because the return value of useEffect should be a cleanup function, not a Promise.
    (async () => {
      try {
        // @ts-ignore - tsc can't figure out that apiParameters matches our apiMethod signature
        const response = await api[apiMethod](...apiParameters);
        setApiData(response);
        setLoadingState('loaded');
      } catch (err) {
        console.error(err); // eslint-disable-line no-console
        setLoadingState('error');
      }
    })();
  }, apiParameters);
github cs8425 / go-bot / admin-web / web-src / src / comp.jsx View on Github external
function PanelListMode(props) {
	const { children, useStyles, handleAddBtn, stopParamFn, ksParamFn, pullFn, dataStore, header, renderRowFn, ...other } = props;
	const classes = useStyles();
	const [anchorEl, setAnchorEl] = useState(null);
	const srvStore = useContext(dataStore);

	// popover for stop
	const handleClick = (ev, val) => {
		console.log('[anchorEl]', ev, val);
		setAnchorEl({
			el: ev.currentTarget,
			val: val,
		});
	};
	const handleClose = () => {
		setAnchorEl(null);
	};
	const handleStop = () => {
		console.log('[stop]', anchorEl.val);
		const val = anchorEl.val;
		const param = stopParamFn(val);
github mihar-22 / preact-hooks-unistore / src / index.js View on Github external
const refEquality = (a, b) =&gt; a === b

// select('foo,bar') creates a function of the form: ({ foo, bar }) =&gt; ({ foo, bar })
const select = (properties) =&gt; {
  properties = properties.split(/\s*,\s*/)

  return state =&gt; {
    const selected = {}
    for (let i = 0; i &lt; properties.length; i++) {
      selected[properties[i]] = state[properties[i]]
    }
    return selected
  }
}

export const StoreContext = createContext(null)

export const StoreProvider = StoreContext.Provider

export const useStore = () =&gt; useContext(StoreContext)

// selector can be a string 'foo,bar' or a function (state =&gt; state.foo)
export const useSelector = (selector, equalityFn = refEquality) =&gt; {
  const store = useStore()
  const [, forceRerender] = useReducer(s =&gt; s + 1, 0)

  const selectorRef = useRef(null)
  const selectedStateRef = useRef(null)
  const onChangeErrorRef = useRef(null)
  const isSelectorStr = (typeof selector === 'string')

  let selectedState
github preactjs / preact / compat / src / render.js View on Github external
let type = vnode.type;
	let props = vnode.props;

	// Apply DOM VNode compat
	if (typeof type != 'function') {
		// Apply defaultValue to value
		if (props.defaultValue) {
			if (!props.value &amp;&amp; props.value !== 0) {
				props.value = props.defaultValue;
			}
			delete props.defaultValue;
		}

		// Add support for array select values: <select value="{[]}">
		if (Array.isArray(props.value) &amp;&amp; props.multiple &amp;&amp; type === 'select') {
			toChildArray(props.children).forEach(child =&gt; {
				if (props.value.indexOf(child.props.value) != -1) {
					child.props.selected = true;
				}
			});
			delete props.value;
		}

		// Normalize DOM vnode properties.
		let shouldSanitize, attrs, i;
		for (i in props) if ((shouldSanitize = CAMEL_PROPS.test(i))) break;
		if (shouldSanitize) {
			attrs = vnode.props = {};
			for (i in props) {
				attrs[
					CAMEL_PROPS.test(i) ? i.replace(/([A-Z0-9])/, '-$1').toLowerCase() : i
				] = props[i];</select>
github matthewmueller / sun / index.js View on Github external
function tag (mixed) {
      if (!arguments.length || (!mixed && mixed !== 0)) {
        return h(name, attrs)
      } else if (mixed.nodeName || arguments.length > 1) {
        return h(name, attrs, flatten(slice(arguments)))
      } else if (isArray(mixed)) {
        return h(name, attrs, flatten(mixed))
      } else if (!isObject(mixed)) {
        return h(name, attrs, mixed)
      } else if (has(mixed, 'toString')) {
        return h(name, attrs, String(mixed))
      }

      // attributes
      attrs = assign(attrs, mixed)
      return tag
    }
github propelml / propel / website / pages.ts View on Github external
const Intro = () =>
  div("intro flex-row",
    div("flex-cell",
      h("h2", {}, "Differential Programming in JavaScript"),
      p(
        b("Propel"), ` provides a GPU-backed numpy-like infrastructure
        for scientific computing in JavaScript.  JavaScript is a fast,
        dynamic language which, we think, could act as an ideal workflow
        for scientific programmers of all sorts.`),
      p(
        headerButton("/docs", "API Ref"),
        // Hide notebook link until more developed.
        // headerButton("/notebook", "Notebook"),
        headerButton("http://github.com/propelml/propel", "Github")
      )
    ),
    div("intro-notebook flex-cell", nb.cell(tanhGrads))
  );