React
Getting started with libZL and React.
Installing
As well as providing the vanilla LibZL library, also available is a React wrapper that brings with it various shortcuts and utils for those using the popular framework.
npm install @zerolight-core/libzl-react --save
The demo below assumes the following items have already been imported:
import LibZL from "@zerolight-core/libzl";
import { ZLBolt,
ZLBoltStreamContainer,
useZLBolt,
useZLBoltStreamState,
useZLBoltOptions,
StreamConnectionState} from "@zerolight-core/libzl-react";
Hooks
The libzl-react library includes various ready made hooks which makes it easy to write neat components
with minimal local state management. The demo below uses useZLBoltStreamState
to provide a button to connect/disconnect.
Demo
Here the options structure is injected for you into defaultDemoOptions
, but see here for example config, or here for more details.
ConnectionWidget = () => { const streamState = useZLBoltStreamState(); const zlbolt = useZLBolt(); const options = useZLBoltOptions(); switch (streamState) { case StreamConnectionState.Ready: return <button onClick={() => zlbolt.disconnect()}>Disconnect</button>; case StreamConnectionState.ConnectionError: return <button onClick={() => zlbolt.connect(options)}>Retry</button>; case StreamConnectionState.Disconnected: return <button onClick={() => zlbolt.connect(options)}>Click to connect</button>; case StreamConnectionState.Connecting: return <button disabled>Connecting...</button>; } } const StreamDemo = () => { // libZL doesn't support SSR if (useIsBrowser()){ const zlbolt = new LibZL().zlbolt("palettedocs"); return (<ZLBolt zlbolt={zlbolt} options={defaultDemoOptions}> <ConnectionWidget/> <ZLBoltStreamContainer/> </ZLBolt>); } return (<div>Unsupported</div>); } render(<StreamDemo/>)
We're using the connect widget here to stop the demo from spamming the service, but in your application, you can connect automatically by adding a connect attribute to the ZLBolt object like this:
<ZLBolt zlbolt={zlbolt} options={defaultDemoOptions} connect>
Try it above to see how ZLBolt then automatically connects.
Provisioning for this demo is light so there may be some delays getting a stream.