- Build
- Features
Preview Controls
Provide content editors with the ability to adjust preview context without editing content.
Preview controls enable content editors to adjust some given context within the preview, without the need to edit the source content. Preview controls are fields that only affect the preview in the current context, and do not affect the source content or context for other editors.
This is useful in a number of scenarios, such as:
- User-context behavior, such as light/dark modes based on operating system preferences
- Editor-only insights, such as showing warnings for missing content
How Preview Controls Work
Most features that customize the visual editing experience require a definition with the Netlify Create configuration file. Preview controls are unique in that they are handled exclusively on the client side.
The injected JavaScript snippet looks for a stackbitPreviewControls
object on the window
object, as an array of individual control definitions.
These controls are then rendered in the proper context in the visual editor. And when an editor changes the value of a control, the onChange
callback is triggered, which can be used to update the preview in any way.
Control Contexts
There are two types of contexts for preview controls: global
and field
. These contexts determine where the control is rendered.
Global Context
The global context is rendered in the top bar of the visual editor, available on all pages. This is useful for controls that affect the entire preview, such as a light/dark mode toggle.
Field Context
The field context requires additional information and has multiple rendering locations. A content source and a document within that source must be specified. Without further details, the control is shown in the page editor, near the title of the document.
If a field path is provided, the control is rendered in the page editor, near the field.
Usage Example
Here is a simple example to demonstrate how preview controls can be used.
Light/Dark Toggle with React
When working with a React framework, you can interact with the global window
object through a useEffect
hook. This also provides the ability to use TypeScript and ensure the control objects are properly defined.
This is a Next.js example that defines a theme
control, which allows editors to toggle between light and dark mode, directly on the _app
component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47