Scoutbar with Context API
Customize the scoutbar experience
Setting up
Try on codesandbox
Initialize the Context
First, we need to create the context, which we can later use to create providers and consumers.
context.js
import React from 'react'; // this is the equivalent to the createStore method of Redux // https://redux.js.org/api/createstore const MyContext = React.createContext(); export default MyContext;
Create the Provider
Once that’s done, we can import the context and use it to create our provider,
which we’re calling Provider. In it, we initialize a state with some values,
which you can share via value prop our provider component. we’re sharing
actions
along with a couple of methods that manipulate the state. Think of
these methods as reducers in Redux.
provider.js
import { useState } from 'React'; import Context from './context'; import { createScoutAction, ScoutBar } from 'scoutbar'; const Provider = ({ children }) => { const [actions, setActions] = useState([ createScoutAction({ title: 'Get Started', href: '/', }), ]); return ( <Context.Provider value={{ actions, setAction: action => setActions(prev => { return [...prev, action]; }), }} > <ScoutBar actions={actions} /> {children} </Context.Provider> ); }; export default Provider;
App.js
import { useContext } from 'React'; import Context from './context'; import { createScoutAction } from 'scoutbar'; export default function App() { const { setActions } = useContext(Context); useEffect(() => { // .....some API Manipulations setActions([ createScoutAction({ label: 'Context Added Action', description: 'Context Added Action with scoutbar', href: '/', }), ]); }, []); return ( <MyProvider> <h1>Hello There</h1> </MyProvider> ); }