Skip to main content

Toggle

A boolean, on any of the three screens.

Import​

import { Toggle } from '@bedrock-core/ui';

Usage​

<Toggle name={'music'} defaultValue={true} />

One component, three mechanisms​

Toggle asks useMechanism('Toggle') what a boolean becomes on the screen it is being drawn on, and draws that. The component is written once; what differs is the host.

ScreenWhat it isHow the value moves
<Form>a native field the engine ownsnothing until submit, then values[name]
<Screen>a button that flips its state and renders the screen againonChange on the press; the player sees the new state on the next present
<Container>a cell of the host's container — the press is an item taken and put straight backonChange on the press; the slots settle in the same tick

So name is what the modal reports under, and on / onChange are what the two press hosts give you. Write all of them and the control moves between screens unchanged: each host uses the ones it can.

Props​

PropTypeDefaultDescription
namestring—Result key on a modal, where it is required; ignored where the press is the answer
defaultValuebooleanfalseWhich way it starts
onboolean—Held by the caller instead of by the control. Only where a press reaches script
onChange(on: boolean) => void—Called with the new state, on the hosts where a press reaches script
backgroundstringthe blank-canvas placeholderThe unchecked face
backgroundHover / backgroundPressed / backgroundLockedstringbackgroundThe unchecked face per state
checkedBackgroundstringthe resolved backgroundThe checked face
checkedHover / checkedLockedstringcheckedBackgroundThe checked face per state

Inherits control props. Geometry is solved by the layout like any other component and encoded for the render pack, so a native widget is positioned by the same flexbox as everything else.

Examples​

In a modal​

<Form onSubmit={({ values }) => setMusic(values.music === true)}>
<Toggle name={'music'} defaultValue={true} />
<Form.Button type={'submit'}>{'Save'}</Form.Button>
</Form>

On a screen of buttons​

function MusicRow(): JSX.Element {
const [on, setOn] = useState(true);

return <Toggle on={on} onChange={setOn} />;
}

The press re-presents the screen, which is how the player sees the flip — a form cannot change while it is open, and an action form is a form.

On a container screen​

<Container entity={'core:console'} padding={8} gap={4}>
<Toggle on={running} onChange={setRunning} />
</Container>

The cell takes one index in the host's container. A press is an item taken and put straight back, so the handler runs and the slots settle in the same tick.

Notes​

The faces resolve by one rule — state ?? base ?? unstyled — so a single background styles every state, and a checkedBackground styles the whole checked side.

@bedrock-core/ore-styled's Toggle and Checkbox are this component with the theme's faces and a caption.