Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'preact' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
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>
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});
}
/** @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 => pattern.test(value) ? onChange(value) : null
const conditionOnSubmit = value => 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 => conditionOnSubmit(evt.target.value)} />
</div>
}
}
// TextInput = radium( TextInput )
const onKeyDown = useKeyListNav({
selected,
onCollapse: collapseNode,
canCollapse: id => {
const node = store.nodes.$.get(id);
return node ? node.children.length > 0 : false;
},
checkCollapsed: id => collapsed.has(id),
onNext: selectNext,
onPrev: selectPrev,
});
const onMouseLeave = useCallback(() => store.actions.highlightNode(null), []);
const ref = useRef(null);
const paneRef = useRef(null);
useEffect(() => {
if (ref.current && paneRef.current) {
const available = ref.current.offsetWidth;
const actual = paneRef.current.offsetWidth;
const diff = actual - available;
if (diff > 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 });
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);
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);
const refEquality = (a, b) => a === b
// select('foo,bar') creates a function of the form: ({ foo, bar }) => ({ foo, bar })
const select = (properties) => {
properties = properties.split(/\s*,\s*/)
return state => {
const selected = {}
for (let i = 0; i < properties.length; i++) {
selected[properties[i]] = state[properties[i]]
}
return selected
}
}
export const StoreContext = createContext(null)
export const StoreProvider = StoreContext.Provider
export const useStore = () => useContext(StoreContext)
// selector can be a string 'foo,bar' or a function (state => state.foo)
export const useSelector = (selector, equalityFn = refEquality) => {
const store = useStore()
const [, forceRerender] = useReducer(s => s + 1, 0)
const selectorRef = useRef(null)
const selectedStateRef = useRef(null)
const onChangeErrorRef = useRef(null)
const isSelectorStr = (typeof selector === 'string')
let selectedState
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 && props.value !== 0) {
props.value = props.defaultValue;
}
delete props.defaultValue;
}
// Add support for array select values: <select value="{[]}">
if (Array.isArray(props.value) && props.multiple && type === 'select') {
toChildArray(props.children).forEach(child => {
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>
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
}
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))
);