<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-PP7S83N" height="0" width="0" style="display:none;visibility:hidden">
Tutorial

Configuring Weavy as a context provider

To enhance the sharing and scope the Weavy configuration in your components, you can make use of a context provider. This guide shows you how to set up a context provider that works with both Web components and React components. Have your project ready, and let's get started.

1. Add a Weavy context provider

We start by adding a Weavy context provider. 

In the getting started guide we configured Weavy using the useWeavy() hook. The hook makes the configuration available to all Weavy components on document level in the DOM. To limit this to only be available to child components, use the <WyContext> context provider instead of the hook.

The context provider works both for all Weavy components and as a standard React context, so you can access and use the Weavy instance in any child react component.

Place the <WyContext> somewhere high up in your component tree, preferably on app level.

Replace the useWeavy hook with <WyContext>
import React from "react";
import { WyContext, WyChat } from "@weavy/uikit-react";
import { tokenFactory } from "./server-actions";
import MyComponent from "./my-component"; 

export default function MyContextProvider({ children }) {
  return (
    <>
      <WyContext
        url="{WEAVY-URL}"
        tokenFactory={tokenFactory}
        >
        { children }
        <MyComponent />
        <WyChat />
      </WyContext>
    </>
  );
}

2. Consume the context

You can consume the context in a child React component. This makes it possible to add additional configuration or use methods from the Weavy instance in any component.

React needs to know which kind of context to consume and this is provided by the WeavyContext definition. Use the definition together with the useContext() hook of the React context API.

import React, { useContext } from "react"
import { WeavyContext } from "@weavy/uikit-react"

export const MyComponent = () => {
  // Requires that weavy is configured using <WyContext> 
  const weavy = useContext(WeavyContext)

  useEffect(() => {
    if (weavy) {
      console.log("We got weavy", weavy.version)
    }
  }, [weavy])

  // ...
  return (
    <></>
  )
}
Make sure to place the <MyComponent> as a child of the <WyContext>.

3. Done!

You now have a scoped Weavy configuration with all the benefits of a React context.

Now it's time to start building for real - read more in the reference to learn how you can customize Weavy.

Support

To access live chat with our developer success team you need a Weavy account.

Sign in or create a Weavy account