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;