I have a React component with prop types like:
type Props = React.HTMLProps<HTMLAnchorElement> & {
to?: string;
};
How do you write the equivalent prop types in SolidJS? I tried this:
type Props = Component<HTMLAnchorElement> & {
to?: string;
};
And it compiles, but it does not have the same built in props as the former such as children.
Solid JS has JSX.IntrinsicElements which provides properties types indexed by tag name:
import { JSX } from 'solid-js';
type Props = JSX.IntrinsicElements['a'] & {
to?: string;
};
You can use JSX.HTMLAttributes<T>:
interface Props extends JSX.HTMLAttributes<HTMLAnchorElement> {}
This comes in handy when you need extend some element with additional properties like the way we do in React:
export interface Props extends JSX.HTMLAttributes<HTMLInputElement> {
value: Accessor<string>;
onInput: JSX.EventHandler<HTMLInputElement, InputEvent>;
icon?: HTMLImageElement;
label?: HTMLImageElement,
}
const Input: Component<Props> = (props) => {
const [_, ...rest] = splitProps(props, ['icon', 'label']);
const handleInput: JSX.EventHandlerUnion<HTMLInputElement, InputEvent> = (event) => {}
return (
<span class={style.wrapper}>
{props.icon && props.icon}
{props.label && props.label}
<input {...rest} value={props.value()} onInput={handleInput} />
</span>
)
};
And for events you have to ways:
const handleInput: JSX.EventHandler<HTMLInputElement, InputEvent> = (event) => {
console.log(event.currentTarget.value);
};
const handleInput: JSX.EventHandlerUnion<HTMLInputElement, InputEvent> = (event) => {
setValue(event.currentTarget.value);
};
Second one works because it as union:
type JSX.EventHandlerUnion<T, E extends Event> =
| JSX.EventHandler<T, E>
| JSX.BoundEventHandler<T, E>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With