Button Click Counter
This example shows you how to implement state with JSX middlewares.
A $withClickCount
directive is implemented in this example, which shows how many times a button has been clicked.
function WithClickCount({ render, props, type }) {
const [count, setCount] = useState(0);
const baseOnClick = props.onClick;
props = {
...props,
onClick: (e) => {
setCount(count + 1);
baseOnClick?.(e);
},
children: [props.children, ` - Clicked ${count} times`],
};
return render(type, props);
}
function withClickCountMiddleware(next, type, props, key) {
if (props.$withClickCount) {
const { $withClickCount, ...restProps } = props;
return <WithClickCount render={next} type={type} props={restProps} key={key} />;
}
return next(type, props, key);
}
addMiddlewares(withClickCountMiddleware);
function App() {
return <button $withClickCount>Click me</button>;
}
http://localhost:3000
Typescript types
declare module 'react' {
interface Attributes {
$withClickCount?: boolean;
}
}