react#createElement TypeScript Examples
The following examples show how to use
react#createElement.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts From plugin-vscode with Apache License 2.0 | 7 votes |
export function renderSamplesList(target: HTMLElement,
openSample: (url: string) => void,
getSamples: () => Promise<BallerinaExampleCategory[]>,
openLink: (url: string) => void) {
const props = {
getSamples,
openLink,
openSample,
};
target.classList.add("composer");
const SamplesListElement = createElement(SamplesList, props);
render(SamplesListElement, target);
}
Example #2
Source File: utils.ts From test with BSD 3-Clause "New" or "Revised" License | 7 votes |
divideChildren = (
children: ReactNode,
Wrapper,
props = {},
): ReactNode | ReactNode[] => {
if (Children.count(children) > 1) {
const combinedChildren = combinePureChildren(children)
const count = combinedChildren.length
return Children.map(combinedChildren, (child, index) => {
if (index < count - 1) {
return createElement(Wrapper, props, child)
}
return child
})
}
return children
}
Example #3
Source File: makeSwitchableMapComponent.ts From ke with MIT License | 6 votes |
export function makeSwitchableMapComponent<Props>(components: Record<string, ComponentType<Props>>): FC<Props> {
return ({ children, ...props }) => {
const provider = useMapProviderContext()
if (provider === null || !(provider in components)) {
throw new Error(
`Unknown map provider ${JSON.stringify(provider)}. Should be one of: ${JSON.stringify(Object.keys(components))}`
)
}
return createElement(components[provider], props as Props, children)
}
}
Example #4
Source File: worker.ts From lucide with ISC License | 6 votes |
getSvg = async ({ cachedIcons, iconName, size = 24 }: { cachedIcons: LucideIcons, iconName: string, size: number }) => {
if (!cachedIcons) {
return;
}
console.log( iconName, size)
const iconNode = cachedIcons.iconNodes[iconName];
if (iconNode) {
const IconComponent = createReactComponent(iconName, iconNode)
const svg = renderToString(createElement(IconComponent, { size }));
parent.postMessage({ pluginMessage: {
type: 'drawIcon',
icon: {
name: iconName,
svg,
size
}
}}, '*')
parent.postMessage({ pluginMessage: {
type: 'close',
}}, '*')
}
}
Example #5
Source File: ListOrder.ts From ke with MIT License | 6 votes |
/**
* Полиморфный компонент для подключения отдельного компонента сортировки к ListView
*
* @remarks
* Требования к компоненту сортировки - {@link RequiredOrderProps}
*/
export function ListOrder<OrderProps extends RequiredOrderProps>({
as: Sorting,
...sortingProps
}: ListOrderProps<OrderProps>): JSX.Element {
const [order, onOrderChange] = useListOrder()
return createElement(Sorting, { ...sortingProps, value: order, onChange: onOrderChange } as unknown as OrderProps)
}
Example #6
Source File: CardWithIcon.tsx From ra-enterprise-demo with MIT License | 6 votes |
CardWithIcon: FC<Props> = props => {
const { icon, title, subtitle, to, children } = props;
const classes = useStyles(props);
return (
<Card className={classes.card}>
<Link to={to}>
<div className={classes.main}>
<Box width="3em" className="icon">
{createElement(icon, { fontSize: 'large' })}
</Box>
<Box textAlign="right">
<Typography
className={classes.title}
color="textSecondary"
>
{title}
</Typography>
<Typography variant="h5" component="h2">
{subtitle || ' '}
</Typography>
</Box>
</div>
</Link>
{children && <Divider />}
{children}
</Card>
);
}
Example #7
Source File: card.call-to-action.tsx From vital with MIT License | 6 votes |
CardCallToAction = <Tag extends keyof JSX.IntrinsicElements = "div">() => forwardRef<HTMLDivElement, CallToActionProps<Tag>>( ({ as, children, ...rest }, ref) => { return ( <div className={styles.callToActionContainer}> {createElement( as, { ...rest, className: styles.callToActionElement, ref }, children )} </div> ); } )
Example #8
Source File: index.tsx From brick-design with MIT License | 6 votes |
function renderMenu(
config: any,
key: string,
enabled: string[],
funMap: any,
style: any,
) {
const { title, icon, shortcutKey, props = {}, type } = config
if (!isString(icon)) return createElement(icon, { key, ...props })
const disabledColor = '#A4A4A4'
const enabledColor = '#000'
const isEnabled = enabled.includes(title)
let func = undefined
if (isEnabled) {
func = funMap[title] || type
}
return (
<Tooltip key={key} mouseEnterDelay={1} title={shortcutKey}>
<div
style={{ color: isEnabled ? enabledColor : disabledColor }}
className={styles['icon-container']}
onClick={func}
key={key}
>
<Icon style={{ fontSize: 18 }} type={icon} />
<span>{title}</span>
</div>
</Tooltip>
)
}
Example #9
Source File: index.tsx From ant-design-pro-V4 with MIT License | 6 votes |
EditableLinkGroup: React.FC<EditableLinkGroupProps> = (props) => {
const { links, linkElement, onAdd } = props;
return (
<div className={styles.linkGroup}>
{links.map((link) =>
createElement(
linkElement,
{
key: `linkGroup-item-${link.id || link.title}`,
to: link.href,
href: link.href,
},
link.title,
),
)}
<Button size="small" type="primary" ghost onClick={onAdd}>
<PlusOutlined /> 添加
</Button>
</div>
);
}
Example #10
Source File: element.ts From starboard-notebook with Mozilla Public License 2.0 | 6 votes |
private setupEditor() {
const editorTheme: typeof theme = { ...theme };
editorTheme.fontFamily = "var(--font-sans)";
editorTheme.fontFamilyMono = "var(--font-mono)";
const math = new Math();
const mathDisplay = new MathDisplay();
return createElement(RichMarkdownEditor, {
defaultValue: this.content.textContent,
placeholder: "Start writing here..",
extensions: [math, mathDisplay],
theme: editorTheme,
onChange: (v) => {
this.content.textContent = v();
},
readOnly: this.content.editable === false,
onClickLink: (href, event) => {
window.open(href, "_blank");
},
embeds: [],
tooltip: undefined as any,
});
}
Example #11
Source File: ForgotPasswordForm.tsx From frontegg-react with MIT License | 6 votes |
ForgotPasswordForm: FC<ForgotPasswordFormProps> = (props) => {
const { renderer } = props;
const { t } = useT();
const { loading, email, error } = useForgotPasswordState();
const { forgotPassword } = useForgotPasswordActions();
if (renderer) {
return createElement(renderer, props);
}
return (
<Formik
initialValues={{ email }}
validationSchema={validateSchema({ email: validateEmail(t) })}
isInitialValid={validateEmail(t).isValidSync(email)}
onSubmit={async ({ email }) => forgotPassword({ email })}
>
<FForm>
<FInput
defaultValue={email}
name='email'
placeholder='[email protected]'
label={t('auth.forgot-password.email-label')}
data-test-id='email-box'
/>
<FButton
type='submit'
formikDisableIfNotDirty={false}
variant='primary'
loading={loading}
data-test-id='submit-btn'
>
{t('auth.forgot-password.remind-me')}
</FButton>
<ErrorMessage error={error} />
</FForm>
</Formik>
);
}
Example #12
Source File: NoneContainer.ts From brick-design with MIT License | 6 votes |
function NoneContainer(vProps: CommonPropsType, ref: any) {
const { renderKey, ...rest } = vProps;
const { pageConfig, componentsMap } = useContext(StaticContext);
const vNode = pageConfig[renderKey];
const { props, hidden } = useCommon(vNode, rest);
// eslint-disable-next-line no-undef
const propsResult = useHandleProps(props, ref);
const { componentName } = vNode;
if (hidden) return null;
return createElement(
get(componentsMap, componentName, componentName),
propsResult,
);
}
Example #13
Source File: emotion.ts From vite-ssr with MIT License | 6 votes |
function clientProvider(context: Context) {
const cache = getCache()
return {
provide(app: ReactElement) {
return createElement(CacheProvider, { value: cache }, app)
},
}
}
Example #14
Source File: index.tsx From reskript with MIT License | 6 votes |
function NavItem({type, active, iconType, onClick}: NavItemProps) {
const click = useCallback(
() => onClick(type),
[onClick, type]
);
return (
<div className={active ? 'item active' : 'item'} onClick={click}>
{createElement(iconType, {className: 'icon'})}
</div>
);
}
Example #15
Source File: Box.tsx From fower with MIT License | 6 votes |
Box: BoxComponent<'div', {}> = forwardRef((props, ref) => {
const { as = 'div', ...rest } = props as any
const parser = new Parser(rest)
const parsedProps = parser.getParsedProps()
const { inline } = store.config
if (inline) {
if (Array.isArray(rest.style)) {
parsedProps.style = [parser.toStyle(), rest.style]
} else {
parsedProps.style = {
...parser.toStyle(),
...rest.style,
}
}
} else {
const finalClassName = parser.getClassNames().join(' ').trim()
if (finalClassName) {
parser.insertRules()
parsedProps.className = finalClassName
}
}
return createElement(as, { ref, ...parsedProps })
}) as any
Example #16
Source File: AutoFields.tsx From uniforms-patternfly with Apache License 2.0 | 6 votes |
export default function AutoFields({
autoField = AutoField,
element = 'div',
fields,
omitFields = [],
...props
}: AutoFieldsProps) {
const { schema } = useForm();
return createElement(
element!,
props,
(fields ?? schema.getSubfields())
.filter((field) => !omitFields!.includes(field))
.map((field) => createElement(autoField!, { key: field, name: field }))
);
}
Example #17
Source File: IconToggleButton.tsx From anchor-web-app with Apache License 2.0 | 6 votes |
function IconToggleButtonBase({
on,
onChange,
onClick,
onIcon,
offIcon,
...buttonProps
}: IconToggleButtonProps) {
return (
<button
{...buttonProps}
onClick={(event) => {
onClick && onClick(event);
onChange(!on);
}}
data-on={on}
>
{on ? createElement(onIcon) : createElement(offIcon)}
</button>
);
}
Example #18
Source File: useHover.test.ts From use-platform with MIT License | 6 votes |
describe('useHover', () => {
const render = createClientRender()
describe('pointer events', () => {
installPointerEvent()
test('should set isHovered after pointer enter and leave', () => {
render(createElement(Fixture))
const node = screen.getByTestId('hoverable')
expect(node).toHaveAttribute('data-hovered', 'false')
fireEvent.hover(node)
expect(node).toHaveAttribute('data-hovered', 'true')
fireEvent.unhover(node)
expect(node).toHaveAttribute('data-hovered', 'false')
})
test('should not set isHovered when disabled', () => {
const { setProps } = render(createElement(Fixture))
const node = screen.getByTestId('hoverable')
setProps({ disabled: true })
fireEvent.hover(node)
expect(node).toHaveAttribute('data-hovered', 'false')
})
})
})
Example #19
Source File: index.tsx From dxvote with GNU Affero General Public License v3.0 | 6 votes |
Result: React.FC<ResultProps> = ({
title,
state,
icon,
subtitle,
extra,
}) => {
const theme = useTheme();
return (
<ResultWrapper>
{icon ||
createElement(IconMap[state], {
size: 32,
color:
state === ResultState.ERROR
? theme?.colors?.red
: theme?.colors?.primary,
})}
<Title>{title}</Title>
<Subtitle>{subtitle}</Subtitle>
{extra}
</ResultWrapper>
);
}
Example #20
Source File: ErrorHandler.tsx From Teyvat.moe with GNU General Public License v3.0 | 6 votes |
render(): ReactElement {
const { error, errorInfo } = this.state;
const { children, errorHandler } = this.props;
// If there is an error, display the error handler
// instead of the base page.
if (error) {
console.error('Error caught, rendering error handler...');
return createElement(errorHandler, { error, errorInfo });
}
// Else, render the child components.
return <>{children}</>;
}
Example #21
Source File: mdx-components.tsx From vanilla-extract with MIT License | 6 votes |
Heading = ({ level, component, children, id }: HeadingProps) => {
const headingElement = createElement(
Box,
{
component: component,
className: useHeadingStyles(level),
},
children,
);
return id ? (
<>
<Box
component="a"
display="block"
id={id}
style={{
visibility: 'hidden',
scrollMarginTop: 120,
}}
/>
<a style={{ textDecoration: 'none' }} href={`#${id}`}>
{headingElement}
</a>
</>
) : (
headingElement
);
}
Example #22
Source File: AdminMenu.tsx From next-right-now-admin with MIT License | 6 votes |
AdminMenu = (props): JSX.Element => {
// XXX Not used yet
console.debug('AdminMenu.props', props);
const { onMenuClick, logout } = props;
const isXSmall = useMediaQuery((theme: any) => theme.breakpoints.down('xs'));
const open = useSelector(state => state.admin.ui.sidebarOpen);
const resources = useSelector(getResources);
return (
<div>
{resources.map(resource => (
<MenuItemLink
key={resource.name}
to={`/${resource.name}`}
primaryText={resource.options && resource.options.label || resource.name}
leftIcon={createElement(resource.icon)}
onClick={onMenuClick}
sidebarIsOpen={open}
/>
))}
<MenuItemLink
to="/custom-route"
primaryText="Miscellaneous"
leftIcon={<LabelIcon />}
onClick={onMenuClick}
sidebarIsOpen={open}
/>
{isXSmall && logout}
</div>
);
}
Example #23
Source File: view.tsx From kinopub.webos with MIT License | 6 votes |
View: React.FC<ViewProps> = ({ component, layout, ...props }) => {
const Layout = useMemo(() => {
if (layout === 'fill') {
return FillLayout;
}
return MainLayout;
}, [layout]);
const render = useMemo<React.FC<RouteComponentProps>>(
() => (routeProps) =>
(
<Layout>
<Suspense fallback={<Spinner />}>{createElement(component!, routeProps)}</Suspense>
</Layout>
),
[component, Layout],
);
return <Route {...props} render={render} />;
}
Example #24
Source File: makePartial.ts From ke with MIT License | 6 votes |
/**
* Создаёт компонент-обёртку с частично или полностью определёнными props
* исходного компонента
*
* @remarks
* Помогает быстро создавать компоненты, совместимые с каким-либо API.
*
* @example
* Определяем `foo`, но не трогаем `bar`
* ```
* // ComponentProps<SourceComponent> = { foo: unknown, bar: unknown }
* const NewComponent = makePartial(SourceComponent, { foo: 'test' })
* // Рендер <NewComponent bar={12} />
* // эквивалентен <SourceComponent foo="test" bar={12} />
* ```
*
* @param source - исходный компонент
* @param predefined - словарь с зафиксированными props
*/
export function makePartial<Props, Predefined extends Partial<Props>>(
source: ComponentType<Props>,
predefined: Predefined
): FC<Omit<Props, keyof Predefined>> {
return (props) => createElement(source, { ...props, ...predefined } as unknown as Props)
}
Example #25
Source File: Data.tsx From plasmic with MIT License | 6 votes |
export function DynamicElement<
Tag extends keyof JSX.IntrinsicElements = "div"
>({
tag = "div",
className,
children,
propSelectors,
...props
}: CommonDynamicProps & ComponentProps<Tag>) {
const computed = _useSelectors(propSelectors);
return createElement(tag, {
children,
...props,
...computed,
className: className + " " + computed.className,
});
}
Example #26
Source File: render.ts From revas with MIT License | 6 votes |
function createRoot(app: React.ReactNode, dom: HTMLElement, canvas: RevasCanvas) {
return createElement(
Root,
{
clientWidth: dom.clientWidth,
clientHeight: dom.clientHeight,
deviceRatio: window.devicePixelRatio,
canvas,
},
app
);
}
Example #27
Source File: makeDefault.ts From ke with MIT License | 6 votes |
/**
* Создаёт компонент-обёртку с частично или полностью определёнными props
* исходного компонента в качестве значений по-умолчанию
*
* @remarks
* Помогает быстро создавать компоненты, совместимые с каким-либо API.
*
* @example
* Определяем `foo`, но не трогаем `bar`
* ```
* // ComponentProps<SourceComponent> = { foo: unknown, bar: unknown }
* const NewComponent = makePartial(SourceComponent, { foo: 'test' })
* // Рендер <NewComponent bar={12} />
* // эквивалентен <SourceComponent foo="test" bar={12} />
* // но можно и <NewComponent bar={12} foo="other test" />
* // эквивалентен <SourceComponent foo="other test" bar={12} />
* ```
*
* @param source - исходный компонент
* @param predefined - словарь с зафиксированными props
*/
export function makeDefault<Props, Predefined extends Partial<Props>>(
source: ComponentType<Props>,
predefined: Predefined
): FC<Props & Predefined> {
return (props) => createElement(source, { ...predefined, ...props })
}
Example #28
Source File: hydrate.tsx From react-loosely-lazy with Apache License 2.0 | 6 votes |
PlaceholderFallbackHydrate = ({
id,
content,
}: PlaceholderFallbackHydrateProps) => {
return (
<>
<input type="hidden" data-lazy-begin={id} />
{content.map((el: HTMLElement, i: number) => {
const { tagName = '', childNodes = [], attributes = [] } = el;
const props = Array.from(attributes).reduce(attrToProp, {
key: String(i),
});
// text node
if (!tagName) return createElement(Fragment, props, el.textContent);
// childless tag
if (!childNodes.length)
return createElement(tagName.toLowerCase(), props);
// tag with content
return createElement(tagName.toLowerCase(), {
...props,
dangerouslySetInnerHTML: { __html: '' },
suppressHydrationWarning: true,
});
})}
<input type="hidden" data-lazy-end={id} />
</>
);
}
Example #29
Source File: htmlProcessor.tsx From dnde with GNU General Public License v3.0 | 6 votes |
htmlProcessor = (html: string): ReactNode => {
if (typeof html !== 'string') {
logger.error('htmlParser: html is not a string');
return React.createElement('div', {}, 'errors: please check dev console') as ReactNode;
}
let doc = domParser.parseFromString(html, 'text/html');
if (doc === null) {
logger.error('htmlParser: doc is null, unable to process html');
return React.createElement('p', {}, 'errors: please check dev console') as ReactNode;
}
return converter(doc as unknown as HTMLElement, 1);
}