Skip to content

Custom Web

It’s possible to render Unistyles without react-native-web dependency by simply creating your own web-only components.

Unfortunately, you still need to install react-native-web in order to run your app, because most of the React Native libraries do not work without it.

For this we recommend following the guidelines provided by Expo.

In order to create custom web components, you need to use getWebProps function. It takes a StyleProp and returns an object with className and ref properties. The className also includes any custom classes defined with _classNames.

src/components/Header.tsx
import { StyleProp, TextStyle } from 'react-native'
import { getWebProps } from 'react-native-unistyles/web'
type HeaderProps = {
style: StyleProp<TextStyle>
children: string
}
export const Header: React.FC<HeaderProps> = ({ style, children }) => {
const { ref, className } = getWebProps(style)
return (
<h1
ref={ref}
className={className}
>
{children}
</h1>
)
}

Or merge multiple styles:

src/components/Header.tsx
import { StyleProp, TextStyle } from 'react-native'
import { StyleSheet } from 'react-native-unistyles'
import { getWebProps } from 'react-native-unistyles/web'
type HeaderProps = {
customStyle: StyleProp<TextStyle>
children: string
}
export const Header: React.FC<HeaderProps> = ({ customStyle, children }) => {
const webProps = getWebProps([customStyle, style.text])
return (
<h1 {...webProps}>
{children}
</h1>
)
}
const style = StyleSheet.create(theme => ({
text: {
color: theme.colors.text,
_web: {
_hover: {
color: theme.colors.primary,
}
}
}
}))

If your component forwards a ref, pass it as the second argument. Unistyles will merge it with its own ref:

src/components/Header.tsx
import { forwardRef } from 'react'
import { StyleProp, TextStyle } from 'react-native'
import { getWebProps } from 'react-native-unistyles/web'
type HeaderProps = {
style: StyleProp<TextStyle>
children: string
}
export const Header = forwardRef<HTMLHeadingElement, HeaderProps>(({ style, children }, forwardedRef) => {
const webProps = getWebProps(style, forwardedRef)
return (
<h1 {...webProps}>
{children}
</h1>
)
})

That’s it! Now you can use your custom web components in your app.