Context-driven styles
StyleX lets you apply styles conditionally. Any condition can be used to do so, Props
, State
or Context
.
The React Context API (and other similar APIs) can be used to avoid prop-drilling and provide conditions that child component can read and apply styles conditionally.
Context can help reduce prop-drilling by sharing state across components. This can often an alternative to using descendent selectors where the same results can be achieved without "styling at a distance".
For example, you can manage the open or closed state of a sidebar using React Context and conditionally apply styles:
Defining context and styles
This file sets up the SidebarContext
and defines the styles for the sidebar in one place.
The context provides a way to share the open/closed state, and the styles determine
the appearance of the sidebar based on that state.
import { createContext } from 'react';
import * as stylex from '@stylexjs/stylex';
export default createContext(false);
Building the sidebar component
The Sidebar
component uses the SidebarContext
to determine its open or closed state
and conditionally applies the appropriate styles.
import React, { useContext } from 'react';
import * as stylex from '@stylexjs/stylex';
import { SidebarContext } from './SidebarContext';
export default function Sidebar({ children }) {
const isOpen = useContext(SidebarContext);
return (
<div {...stylex.props(styles.base, isOpen ? styles.open : styles.closed)}>
{children}
</div>
);
}
const styles = stylex.create({
base: {...},
open: {
width: 250,
},
closed: {
width: 50,
},
});
Using the sidebar in a parent component
The App
component manages the sidebar's open/closed state and provides it to
child components through SidebarContext.Provider
. A button toggles the sidebar state dynamically.
import React, { useState } from 'react';
import SidebarContext from './SidebarContext';
import Sidebar from './Sidebar';
export default function App() {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
return (
<SidebarContext.Provider value={isSidebarOpen}>
<button onClick={() => setIsSidebarOpen(open => !open)}>
Toggle Sidebar
</button>
<Sidebar>
<p>Sidebar Content</p>
</Sidebar>
</SidebarContext.Provider>
);
}