diff --git a/docs/latest/examples/client-side-components-and-libraries.md b/docs/latest/examples/client-side-components-and-libraries.md new file mode 100644 index 00000000..8cc42763 --- /dev/null +++ b/docs/latest/examples/client-side-components-and-libraries.md @@ -0,0 +1,181 @@ +--- +description: | + Client side components and libraries +--- + +Some components depend on client environments, browser-specific features, or +dynamic user interactions, making them incompatible or non-functional during +server-side rendering. + +By employing conditional rendering and state management techniques, we can +ensure graceful handling of library or data loading, improving workflow and +usability of such components. + +Let's explore an example utilizing this solution with Leaflet, a popular mapping +library, in a Fresh application. The objective is to ensure the proper rendering +of Leaflet components on the client side while gracefully handling them on the +server side. + +The full code is available at the end of the page + +## Explanation + +The first step is creating the context variable to enhance usability across +various components within a Fresh application. By initializing these variables +with a null value and integrating type references, developers can streamline the +use of client side features while adapting to scenarios where server side +rendering might not be feasible. + +> [warn]: Proper typing might not be easily available, so we might need to +> define our own types or not use types at all. + +```ts +export const leafletContext = createContext(null); +``` + +Then, we should implement a Provider Component, this will handle loading and +passing down values to be used in other components, other than that, we also +need to handle the server side case as well. + +In this example, for the server side we are simply rendering a placeholder in +place of our component tree. As for the context value, we are using html tags to +inject the library on the window and a onLoad callback to set the value of our +state, and this value will be handled/shared with our other components. + +> [warn]: Be careful with providers, the manner in which they load/inject both +> script and css may cause issues. Leaflet, for instance, will throw errors if +> we try to load it again. + +```tsx +function LeafletProvider(props: { children: ComponentChildren }) { + if (!IS_BROWSER) { + return ( +

Leaflet must be loaded on the client. No children will render

+ ); + } + const [value, setValue] = useState(null); + return ( + <> + {/* Load Leaflet CSS */} + + {/* Load Leaflet JS */} +