Reputation: 2222
I have a code which looks like this:
import * as React from "react";
import "./styles.css";
import { Tooltip, Button } from "@material-ui/core";
export default function App() {
return (
<>
<Tooltip title="Same text" arrow>
<Button>One</Button>
</Tooltip>
<Tooltip title="Same text" arrow>
<Button>Two</Button>
</Tooltip>
</>
);
}
https://codesandbox.io/s/focused-microservice-4e59z?file=/src/App.tsx:0-346
Since both Tooltips have exactly the same properties but different children, I would like to define a specialized component and rewrite my code to something like this:
import * as React from "react";
import "./styles.css";
import { Tooltip, Button } from "@material-ui/core";
function MyTooltip(child: JSX.Element) {
return (<Tooltip title="Same text" arrow>{child}</Tooltip>);
}
export default function App() {
return (
<>
<MyTooltip>
<Button>One</Button>
</MyTooltip>
<MyTooltip>
<Button>Two</Button>
</MyTooltip>
</>
);
}
https://codesandbox.io/s/eager-worker-xrqsq?file=/src/App.tsx
But this leads to a compilation error: Type '{ children: Element; }' is missing the following properties from type 'Element': type, props, keys(2739)
which I can't fix.
Upvotes: 0
Views: 729
Reputation: 2222
Found a nice approach (defaultProps) which also allows overriding any Tooltip properties on MyTooltip:
import * as React from "react";
import "./styles.css";
import { Tooltip, Button, TooltipProps } from "@material-ui/core";
function MyTooltip(props: TooltipProps) {
return <Tooltip {...props} />;
};
MyTooltip.defaultProps = {
title: "Same text",
arrow: true
}
export default function App() {
return (
<>
<MyTooltip arrow={false}>
<Button>One</Button>
</MyTooltip>
<MyTooltip title="Overriden text">
<Button>Two</Button>
</MyTooltip>
</>
);
}
https://codesandbox.io/s/defaultprops-lythg?file=/src/App.tsx
Upvotes: 0
Reputation: 4380
interface MyTooltipProps {
children: JSX.Element;
}
const MyTooltip: React.FC<MyTooltipProps> = ({ children }) => {
return (
<Tooltip title="Same text" arrow>
{children}
</Tooltip>
);
};
Upvotes: 2