Styled Components and Emotion
OneJS provides APIs that are equivalent to the styled
, css
, and attr
APIs from Styled Components, and also the css
API from Emotion.
These are available from preact/styled
(technically, it's provided by the onejs-preact
package, but the shortcut mappings in tsconfig.json allows you to just use preact/styled
).
TSX
import { h, render } from "preact"
import styled, { CompType, uss } from "preact/styled"
const Button = styled.button`
border-width: 0;
border-radius: 3px;
background-color: green;
color: white;
&:hover {
background-color: red;
}
${props => props.primary && uss`
background-color: white;
color: black;
`}
` as CompType<{ primary: boolean }, JSX.Button>
render(<Button text="Hello!" primary />, document.body)
attr
also works as you'd expect:
TSX
import styled from "preact/styled"
import { h, render } from "preact"
const Jin = styled.button.attrs(props => ({
text: props.foo
}))`
color: red;
`
const Cup = styled(Jin).attrs(props => ({
text: "Foooooo",
bar: props.bar || 50
}))`
font-size: ${props => props.bar}px;
`
render(<Cup foo="My Text" />, document.body)
Emotion's css
(which is different from Styled Components' css
) is available as emo
from onejs/styled
:
TSX
import { emo } from "onejs"
import { h, render } from "preact"
const Foo = (props) => {
return <div class={emo`
font-size: ${props.size ?? 10}px;
color: red;
`}>Hello</div>
}
render(<Foo size={30} />, document.body)
Please get in our Discord to share what other APIs you'd like to see supported.