Skip to main content

Contextual styles

Contextual styles are an effective way to dynamically adapt styles based on a component's state or its environment. Here are some approaches to achieve this:

Using Context

Context can help reduce prop-drilling by sharing state across components. 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';

const SidebarContext = createContext(false);

const styles = stylex.create({
sidebarOpen: {
width: '250',
},
sidebarClosed: {
width: '50',
},
});

export { SidebarContext, styles };

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, styles } from './SidebarContext';


function Sidebar({ children }: { children: React.ReactNode }) {
const isOpen = useContext(SidebarContext);

return (
<div {...stylex.props(isOpen ? styles.sidebarOpen : styles.sidebarClosed)}>
{children}
</div>
);
}

export default Sidebar;

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';

function App() {
const [isSidebarOpen, setIsSidebarOpen] = useState(false);

return (
<SidebarContext.Provider value={isSidebarOpen}>
<button onClick={() => setIsSidebarOpen(!isSidebarOpen)}>
Toggle Sidebar
</button>
<Sidebar>
<p>Sidebar Content</p>
</Sidebar>
</SidebarContext.Provider>
);
}

export default App;