Creating components with class
as an argument?
#4059
-
Hi, I'm trying to create functional components with the option to pass in style as a property. With default elements, you pass classes with the class keyword. function App() {
return <div class="main">Hello</div>
} But I can't figure out how to pass a
Something like that. The MyButton component has default styling, which can be overwritten/customized by the caller. This is a pattern pretty common in Tailwind and React with But I can't figure out how to do it easily in Preact. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I'm not quite sure I follow, are you asking about types (your commented out import type { JSX } from 'preact';
interface ButtonProps extends JSX.HTMLAttributes<HTMLButtonElement> {
type: 'rounded' | 'square';
}
function MyButton(props: ButtonProps) {
const btnStyle =
props.type === 'rounded' ? 'btn btn-rounded' : 'btn btn-square';
return <button class={btnStyle}>Hello</button>;
} |
Beta Was this translation helpful? Give feedback.
I'm not quite sure I follow, are you asking about types (your commented out
extends
) or usingclass
as a prop? If the former, see the code sample below, if the latter, everything works the same as it would in React. Obviously, you can't destructureclass
like that, it being a reserved word and all in JS. You can use any other name, avoid destructuring, destructure but assign to another name, etc., however.