Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A React library to make integration of Watson Assistant web chat with a React application easy.

License

NotificationsYou must be signed in to change notification settings

watson-developer-cloud/assistant-web-chat-react

Repository files navigation

License: MITBuild and Test

IBM watsonx Assistant web chat with React

@ibm-watson/assistant-web-chat-react is a React library to extend theweb chat feature ofIBM watsonx Assistant within your React application. This makes it easier to provide user-defined response types written in React, add content to custom elements with React, have the web chat and your site communicate more easily, and more.

The primary utility provided by this library is theWebChatContainer functional component. This component will load and render an instance of web chat when it is mounted and destroy that instance when unmounted.

Table of contents

Installation

To install usingnpm:

npm install @ibm-watson/assistant-web-chat-react

Or usingyarn:

yarn add @ibm-watson/assistant-web-chat-react

Using WebChatContainer

Basic example

TheWebChatContainer function component is intended to make it as easy as possible to include web chat in your React application. To use, you simply need to render this component anywhere in your application and provide theweb chat configuration options object as a prop.

importReactfrom'react';import{WebChatContainer,setEnableDebug}from'@ibm-watson/assistant-web-chat-react';constwebChatOptions={integrationID:'XXXX',region:'XXXX',serviceInstanceID:'XXXX',// subscriptionID: 'only on enterprise plans',// Note that there is no onLoad property here. The WebChatContainer component will override it.// Use the onBeforeRender or onAfterRender prop instead.};// Include this if you want to get debugging information from this library. Note this is different than// the web chat "debug: true" configuration option which enables debugging within web chat.setEnableDebug(true);functionApp(){return<WebChatContainerconfig={webChatOptions}/>;}

Accessing instance methods

You can use theonBeforeRender oronAfterRender props to get access to the instance of web chat if you need call instance methods later. This example renders a button that toggles web chat open and is only rendered after the instance has become available.

importReact,{useCallback,useState}from'react';import{WebChatContainer}from'@ibm-watson/assistant-web-chat-react';constwebChatOptions={/* Web chat options */};functionApp(){const[instance,setInstance]=useState(null);consttoggleWebChat=useCallback(()=>{instance.toggleOpen();},[instance]);return(<>{instance&&(<buttontype="button"onClick={toggleWebChat}>          Toggle web chat</button>)}<WebChatContainerconfig={webChatOptions}onBeforeRender={(instance)=>onBeforeRender(instance,setInstance)}/></>);}functiononBeforeRender(instance,setInstance){// Make the instance available to the React components.setInstance(instance);// Do any other work you might want to do before rendering. If you don't need any other work here, you can just use// onBeforeRender={setInstance} in the component above.}

User defined responses

This component is also capable of managing user defined responses. To do so, you need to pass arenderUserDefinedResponse function as a render prop. This function should return a React component that will render the content for the specific message for that response. You should make sure that theWebChatContainer component does not get unmounted in the middle of the life of your application because it will lose all user defined responses that were previously received by web chat.

You should treat therenderUserDefinedResponse prop like any typical React render prop; it is different from theuserDefinedResponse event or a typical event handler. The event is fired only once when web chat initially receives the response from the server. TherenderUserDefinedResponse prop however is called every time the App re-renders and it should return an up-to-date React component for the provided message item just like the render function would for a typical React component.

Note: in web chat 8.2.0, the custom response event was renamed fromcustomResponse touserDefinedResponse. If this library detects you are using a prior version of web chat, it will use thecustomResponse event instead ofuserDefinedResponse.

importReactfrom'react';import{WebChatContainer}from'@ibm-watson/assistant-web-chat-react';constwebChatOptions={/* Web chat options */};functionApp(){return<WebChatContainerrenderUserDefinedResponse={renderUserDefinedResponse}config={webChatOptions}/>;}functionrenderUserDefinedResponse(event){// The event here will contain details for each user defined response that needs to be rendered.// The "user_defined_type" property is just an example; it is not required. You can use any other property or// condition you want here. This makes it easier to handle different response types if you have more than// one user defined response type.if(event.data.message.user_defined&&event.data.message.user_defined.user_defined_type==='my-custom-type'){return<div>My custom content</div>}}

A note on config objects creating multiple web chat instances

TheWebChatContainer component will destroy the current instance of web chat and create a new one if the config object changes. This check is a strict equal check on the config object itself; it does not compare the properties inside of the config object. A common pitfall to fall into is creating the config object inside the component and passing it toWebChatContainer. This will cause the container to destroy and recreate the web chat instance every time the component renders because the config object will change.

Here's an example:

importReact,{useState}from'react';import{WebChatContainer,setEnableDebug}from'@ibm-watson/assistant-web-chat-react';// Enable debugging so we can see what WebChatContainer is doing.setEnableDebug(true);functionApp(){const[value,setValue]=useState(0);constconfig={integrationID:'XXX',region:'XXX',serviceInstanceID:'XXX',};return(<div><buttontype="button"onClick={()=>setValue(value+1)}>        Value:{value}</button><WebChatContainerconfig={config}/></div>);}exportdefaultApp;

If you click the button in this example, it will trigger a re-render of the component and if you look in the console output you will see the following message (because ofsetEnableDebug(true)):

[IBM watsonx Assistant WebChatContainer] Creating a new web chat due to configuration change.

The quick solution to this is to move the config object outside of the component:

importReact,{useState}from'react';import{WebChatContainer,setEnableDebug}from'@ibm-watson/assistant-web-chat-react';setEnableDebug(true);constconfig={integrationID:'XXX',region:'XXX',serviceInstanceID:'XXX',};functionApp(){const[value,setValue]=useState(0);return(<div><buttontype="button"onClick={()=>setValue(value+1)}>        Value:{value}</button><WebChatContainerconfig={config}/></div>);}exportdefaultApp;

However this may not always be feasible because you may have a use case where the config object is not static but contains data that is passed into your component from outside. In that case, you will need to memoize the config object to avoid creating a new one unnecessarily. Also be careful with properties that are functions such as theonError property. Those properties need to be memoized as well, usually by usinguseCallback.

importReact,{useState,useMemo}from'react';import{WebChatContainer,setEnableDebug}from'@ibm-watson/assistant-web-chat-react';setEnableDebug(true);functionMyComponent({ integrationID, region, serviceInstanceID}){const[value,setValue]=useState(0);// Only create a new config object when the configuration properties change.constconfig=useMemo(()=>({      integrationID,      region,      serviceInstanceID,}),[integrationID,region,serviceInstanceID],);return(<div><buttontype="button"onClick={()=>setValue(value+1)}>        Value:{value}</button><WebChatContainerconfig={config}/></div>);}functionApp(){return(<MyComponentintegrationID="XXX"region="us-south"serviceInstanceID="XXX"/>);}exportdefaultApp;

WebChatCustomElement

This library provides the componentWebChatCustomElement which can be used to aid in rendering web chat inside a custom element. This is needed if you want to be able to change the location where web chat is rendered. This component will render an element in your React app and use that element as the custom element for rendering web chat.

The default behavior of this component will add and remove a classname from the web chat main window as well as your custom element to control the visibility of web chat when it is opened or closed. It will also inject astyle tag into your application to define the rules for these classnames. When web chat is closed, a classname will be added to the web chat main window to hide the element and a classname will be added to your custom element to set its width and height to 0 so it doesn't take up space. Note that the custom element should remain visible if you want to use the built-in web chat launcher which is also contained in your custom element. If you don't want these behaviors, then provide your ownonViewChange prop toWebChatCustomElement and provide your own logic for controlling the visibility of web chat. If you want custom animations when web chat is opened and closed, this would be the mechanism to do that.

The simplest example is this:

importReactfrom'react';import{WebChatCustomElement}from'@ibm-watson/assistant-web-chat-react';import'./App.css';constwebChatOptions={/* Web chat options */};functionApp(){return<WebChatCustomElementclassName="MyCustomElement"config={webChatOptions}/>;}
.MyCustomElement {position: absolute;left:100px;top:100px;width:500px;height:500px;}

API

WebChatContainer API

TheWebChatContainer function is a functional component that will load and render an instance of web chat when it is mounted and destroy that instance when unmounted. If the web chat configuration options change, it will also destroy the previous web chat and create a new one with the new configuration. It can also manage React portals for user defined responses.

Note that this component will call theweb chat render method for you. You do not need to call it yourself. You can use theonBeforeRender oronAfterRender prop to execute operations before or after render is called.

Props

WebChatContainer has the following props.

AttributeRequiredTypeDescription
configYesobjectTheweb chat configuration options object. Note that anyonLoad property will be ignored. If this prop is changed and a new object provided, then the current web chat will be destroyed and a new one created with the new object.
instanceRefNoMutableRefObjectA convenience prop that is a reference to the web chat instance. This component will set the value of this ref using thecurrent property when the instance has been created.
onBeforeRenderNofunctionThis is a callback function that is called after web chat has been loaded and before therender function is called. This function is passed a single argument which is the instance of web chat that was loaded. This function can be used to obtain a reference to the web chat instance if you want to make use of the instance methods that are available.
onAfterRenderNofunctionThis is a callback function that is called after web chat has been loaded and after therender function is called. This function is passed a single argument which is the instance of web chat that was loaded. This function can be used to obtain a reference to the web chat instance if you want to make use of the instance methods that are available.
renderUserDefinedResponseNofunctionThis function is a callback function that will be called by this container to render user defined responses. If this prop is provided, then the container will listen for user defined response events from web chat and will generate a React portal for each event. This function will be called once during component render for each user defined response event. This function takes two arguments. The first is theuser defined response event that triggered the user defined response. The second is a convenience argument that is the instance of web chat. The function should return aReactNode that renders the user defined content for the response.

WebChatCustomElement inherits all of the props fromWebChatContainer. It also has the following additional optional props.

AttributeTypeDescription
classNamestringAn optional classname that will be added to the custom element.
idstringAn optional id that will be added to the custom element.
onViewChangefunctionAn optional listener for "view:change" events. Such a listener is required when using a custom element in order to control the visibility of the web chat main window. If no callback is provided here, a default one will be used that uses some classnames to control web chat and your custom element. You can provide a different callback here if you want custom behavior such as an animation when the main window is opened or closed. Note that this function can only be provided before web chat is loaded. After web chat is loaded, the event handler will not be updated. See the web chatview:change documentation for more information. Also see thetutorial for using animiations with custom elements for an example of what can be done here.

Debugging

In addition to the props above, theWebChatContainer component can output additional debug information. To enable this output, call thesetEnableDebug function which is exported from this library.

setEnableDebug(true);functionApp(){return<WebChatContainerconfig={webChatOptions}/>;}

Additional resources

License

This package is available under theMIT License.

About

A React library to make integration of Watson Assistant web chat with a React application easy.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors6


[8]ページ先頭

©2009-2025 Movatter.jp