ld-react
The quickest and easiest way to integrate launch darkly with react 🎉
Why this package?
- Easy and fast to use. Two steps to get feature flags into your react app.
- Supports subscription out of the box. You get live changes on the client as you toggle features.
- You automatically get camelCased keys as opposed to the default kebab-cased.
- No need for redux! This package uses the new context api which is available from react ^16.3.0.
Dependency
This needs react ^16.4.0! It won't work otherwise.
Installation
yarn add ld-react
Quickstart
-
Wrap your root app
withFlagProvider
:;const App =<div><Home /></div>;App clientSideId: 'your-client-side-id'; -
Wrap your component
withFlags
to get them via props:;const Home = {// flags are available via props.flagsreturn propsflagsdevTestFlag ? <div>Flag on</div> : <div>Flag off</div>;};Home;
That's it!
API
withFlagProvider(Component, {clientSideId, user, options})
This is a hoc which accepts a component and a config object with the above properties.
Component
and clientSideId
are mandatory.
For example:
; const App = <div> <Home /> </div>; App clientSideId: 'your-client-side-id';
The user
property is optional. You can initialise the sdk with a custom user by specifying one. This must be an object containing
at least a "key" property. If you don't specify a user object, ld-react will create a default one that looks like this:
const defaultUser = key: uuid // random guid ip: ip custom: browser: userAgentParserbrowsername device ;
For more info on the user object, see here.
The options
property is optional. It can be used to pass in extra options such as Bootstrapping.
For example:
;
withFlags(Component)
This is a hoc which passes all your flags to the specified component via props. Your flags will be available
as camelCased properties under this.props.flags
. For example:
; { return <div> thispropsflagsdevTestFlag ? // Look ma, feature flag! <div>Flag on</div> : <div>Flag off</div> </div> ; } Home;
ldClient
Internally the ld-react initialises the ldclient-js sdk and stores a reference to the resultant ldClient object in memory. You can use this object to access the official sdk methods directly. For example, you can do things like:
; // track goals ldClient; // change user context ldClient; // ... other implementation
For more info on changing user context, see the official documentation.
Example
Check the example for a fully working spa with
react and react-router. Remember to enter your client side sdk in the client root app file
and create a test flag called dev-test-flag
before running the example!