📣 Introducing TypeScript Dash component generation

Hi everyone,

I want to share a new way to create Dash components using TypeScript to define props.

To use the typescript generation, add --ts argument to dash-generate-components, ie: dash-generate-components path/to/components projectname --ts. All components should be in .tsx.

Currently in PR, but you can try it now with this cookiecutter template:

cookiecutter gh:t4rk1n/dash-typescript-component-template

The template requirements.txt will install Dash from the PR, as such the setup will error, the components can still be generated but Dash will fail to start. You can install the components library with pip install -e . in another venv with the latest Dash version installed to test the components.

Example TypeScript component:

import React, {useCallback} from 'react';

type Props = {
    id?: string;
    /**
     * JSX.Element is equivalent to PropTypes.node, also React.ReactNode & React.ReactElement.
     */
    children: JSX.Element;
    n_clicks?: number;
    class_name?: string;
    /**
     * Call to update props in callbacks.
     */
    setProps?: (props: Record<string, any>) => void;
}

const MyComponent = (props: Props) => {
    const {
        setProps,
        children,
        n_clicks,
        id,
        class_name,
    } = props;

    const onClick = useCallback(
        () => setProps({n_clicks: n_clicks + 1}),
        [n_clicks]
    );

    return (
        <div
            id={id}
            className={class_name}
            onClick={onClick}
        >
            {children}
        </div>
    )
}


MyComponent.defaultProps = {
    n_clicks: 0,
}

export default MyComponent;
10 Likes

This is great. I’ll try it with dash-mantine-components.

This looks great, and I would love to re-write my components with TypeScript. I had a quick play with it, and I seem to get resolve issues whenever I try to write a component with a dependent library. Do you have any examples of using this as a wrapper for another library?

Here’s a wrapper I created for react-colorful:

3 Likes

Sorry to bump an old conversation, but I’ve just started playing around with this and am really enjoying it. The one thing I’m missing in the process is to be able to run a javascript demo (using webpack-serve). I know very, very little about web development, is it possible to re-enable this? I’ve messed around without success so far.