### Install watsonx Assistant web chat React library Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Installs the `@ibm-watson/assistant-web-chat-react` library using either npm or yarn package managers. This is the first step to integrating the web chat into a React application. ```bash npm install @ibm-watson/assistant-web-chat-react ``` ```bash yarn add @ibm-watson/assistant-web-chat-react ``` -------------------------------- ### Register Event Listeners for Web Chat Customization in React Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Shows how to register event listeners using the web chat instance to track user interactions and customize behavior. This example demonstrates handling events like message sending, receiving, view changes, conversation restarts, and errors. It uses the `onBeforeRender` prop of `WebChatContainer` to access the instance and attach handlers. ```jsx import React, { useCallback } from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', }; function App() { const handleBeforeRender = useCallback((instance) => { // Track when messages are sent instance.on({ type: 'send', handler: (event) => { console.log('Message sent:', event.data.input.text); // Send to analytics if (window.analytics) { window.analytics.track('chat_message_sent', { message: event.data.input.text }); } } }); // Track when messages are received instance.on({ type: 'receive', handler: (event) => { console.log('Message received:', event.data); } }); // Track view changes (open/close) instance.on({ type: 'view:change', handler: (event) => { if (event.newViewState.mainWindow) { console.log('Chat opened'); if (window.analytics) { window.analytics.track('chat_opened'); } } else { console.log('Chat closed'); if (window.analytics) { window.analytics.track('chat_closed'); } } } }); // Handle conversation restart instance.on({ type: 'restartConversation', handler: () => { console.log('Conversation restarted'); } }); // Handle errors instance.on({ type: 'error', handler: (event) => { console.error('Web chat error:', event); // Report to error tracking service if (window.errorTracker) { window.errorTracker.captureException(event.error); } } }); }, []); return ( ); } export default App; ``` -------------------------------- ### Implement Custom View Change Animations for Web Chat (React) Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt This example shows how to implement custom animations when the IBM Watson Assistant web chat opens or closes using the `onViewChange` callback with `WebChatCustomElement` in a React application. It utilizes CSS animations triggered by class changes on the custom element. This approach requires the `@ibm-watson/assistant-web-chat-react` library and associated CSS. The `useRef` and `useCallback` hooks are used for efficient handling of the element reference and callback. ```jsx import React, { useCallback, useRef } from 'react'; import { WebChatCustomElement } from '@ibm-watson/assistant-web-chat-react'; import './AnimatedChat.css'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', }; function App() { const customElementRef = useRef(null); const handleViewChange = useCallback((event, instance) => { const mainWindow = instance.elements.getMainWindow(); const customElement = customElementRef.current; if (event.newViewState.mainWindow) { // Opening animation customElement.classList.add('chat-opening'); customElement.classList.remove('chat-closed'); mainWindow.removeClassName('hidden'); // Remove opening class after animation completes setTimeout(() => { customElement.classList.remove('chat-opening'); customElement.classList.add('chat-open'); }, 300); } else { // Closing animation customElement.classList.add('chat-closing'); customElement.classList.remove('chat-open'); setTimeout(() => { customElement.classList.remove('chat-closing'); customElement.classList.add('chat-closed'); mainWindow.addClassName('hidden'); }, 300); } }, []); const setRef = useCallback((element) => { customElementRef.current = element; }, []); return (
); } export default App; ``` ```css /* AnimatedChat.css */ .animated-chat { position: fixed; right: 20px; bottom: 20px; width: 350px; height: 500px; transition: all 0.3s ease-in-out; } .animated-chat.chat-closed { width: 0; height: 0; opacity: 0; } .animated-chat.chat-opening { animation: slideInUp 0.3s ease-out; } .animated-chat.chat-closing { animation: slideOutDown 0.3s ease-in; } @keyframes slideInUp { from { transform: translateY(100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } } @keyframes slideOutDown { from { transform: translateY(0); opacity: 1; } to { transform: translateY(100%); opacity: 0; } } #WACContainer.WACContainer .hidden { display: none; } ``` -------------------------------- ### Render Web Chat in Custom Element using React Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md The WebChatCustomElement component from '@ibm-watson/assistant-web-chat-react' allows rendering web chat within a specified custom HTML element in a React application. It manages the visibility and styling of the chat window based on its state. You can customize its behavior by providing an `onViewChange` prop. The example shows basic usage with className and config props. ```javascript import React from 'react'; import { WebChatCustomElement } from '@ibm-watson/assistant-web-chat-react'; import './App.css'; const webChatOptions = { /* Web chat options */ }; function App() { return ; } ``` ```css .MyCustomElement { position: absolute; left: 100px; top: 100px; width: 500px; height: 500px; } ``` -------------------------------- ### Memoize Web Chat Configuration with useMemo and useCallback (React) Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Illustrates how to use React's `useMemo` and `useCallback` hooks to optimize the recreation of the Watson Assistant web chat instance. By memoizing the configuration object and event handlers, unnecessary re-renders caused by prop changes are prevented, leading to improved performance. This is particularly useful when the web chat configuration depends on dynamic props or when passing callbacks to components. ```jsx import React, { useState, useMemo, useCallback } from 'react'; import { WebChatContainer, setEnableDebug } from '@ibm-watson/assistant-web-chat-react'; setEnableDebug(true); function MyComponent({ integrationID, region, serviceInstanceID, userID }) { const [value, setValue] = useState(0); // Memoize config object to only recreate when actual config properties change const config = useMemo(() => ({ integrationID, region, serviceInstanceID, identityToken: userID ? `user-${userID}` : undefined, onError: (error) => { console.error('Web chat error:', error); } }), [integrationID, region, serviceInstanceID, userID]); // Memoize callbacks to prevent config recreation const handleBeforeRender = useCallback((instance) => { console.log('Web chat loaded with version:', instance.getWidgetVersion()); }, []); return (
); } function App() { return ( ); } export default App; ``` -------------------------------- ### Web Chat: Memoizing Dynamic Config Object (React) Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Illustrates how to memoize a dynamic configuration object using `useMemo` in React. This is essential when configuration properties are passed from outside and avoids unnecessary re-creation of the config object and subsequent `WebChatContainer` re-initialization. ```javascript import React, { useState, useMemo } from 'react'; import { WebChatContainer, setEnableDebug } from '@ibm-watson/assistant-web-chat-react'; setEnableDebug(true); function MyComponent({ integrationID, region, serviceInstanceID }) { const [value, setValue] = useState(0); // Only create a new config object when the configuration properties change. const config = useMemo( () => ({ integrationID, region, serviceInstanceID, }), [integrationID, region, serviceInstanceID], ); return (
); } function App() { return ( ); } export default App; ``` -------------------------------- ### Render WebChatContainer with basic configuration Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Demonstrates the basic usage of the `WebChatContainer` component from the `@ibm-watson/assistant-web-chat-react` library. It requires a configuration object with integration details and optionally enables debug logging for the library. ```javascript import React from 'react'; import { WebChatContainer, setEnableDebug } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { 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); function App() { return ; } ``` -------------------------------- ### Access Web Chat Instance Methods via Callbacks Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Shows how to access and interact with the web chat instance using `onBeforeRender` or `onAfterRender` callbacks. This allows invoking methods like `toggleOpen()` or sending messages via `send()`. ```jsx import React, { useCallback, useState } from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', }; function App() { const [instance, setInstance] = useState(null); const handleBeforeRender = useCallback((webChatInstance) => { // Store instance for later use setInstance(webChatInstance); // Optional: customize web chat before rendering webChatInstance.on({ type: 'pre:send', handler: (event) => { console.log('User is sending:', event.data); } }); }, []); const toggleWebChat = useCallback(() => { if (instance) { instance.toggleOpen(); } }, [instance]); const sendMessage = useCallback(() => { if (instance) { instance.send({ input: { text: 'Hello from React!' } }); } }, [instance]); return (
{instance && ( <> )}
); } export default App; ``` -------------------------------- ### Access Web Chat Instance with instanceRef Prop in React Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Demonstrates using the `instanceRef` prop to access the web chat instance directly in React components. This allows imperative control over the chat window, such as opening it, sending messages, or restarting the conversation. It utilizes `useRef` and `useCallback` hooks for managing the instance and defining actions. ```jsx import React, { useRef, useCallback } from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', }; function App() { const webChatInstanceRef = useRef(null); const openChat = useCallback(() => { if (webChatInstanceRef.current) { webChatInstanceRef.current.openWindow(); } }, []); const sendHelp = useCallback(() => { if (webChatInstanceRef.current) { webChatInstanceRef.current.send({ input: { text: 'I need help' } }); } }, []); const restartChat = useCallback(() => { if (webChatInstanceRef.current) { webChatInstanceRef.current.restartConversation(); } }, []); return (
); } export default App; ``` -------------------------------- ### Access Web Chat instance for advanced control Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Shows how to access the web chat instance using the `onBeforeRender` prop of the `WebChatContainer` component. This allows for programmatic control, such as toggling the chat's visibility, after the instance is available. ```javascript import React, { useCallback, useState } from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { /* Web chat options */ }; function App() { const [instance, setInstance] = useState(null); const toggleWebChat = useCallback(() => { instance.toggleOpen(); }, [instance]); return ( <> {instance && ( )} onBeforeRender(instance, setInstance)} /> ); } function onBeforeRender(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. } ``` -------------------------------- ### Render Web Chat in Custom Position using WebChatCustomElement (React) Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt This snippet demonstrates how to use the `WebChatCustomElement` component to render the IBM Watson Assistant web chat at a specific position and with custom dimensions within a React application. It requires the `@ibm-watson/assistant-web-chat-react` library and CSS for styling. The component manages the chat's visibility and positioning, allowing for flexible UI integration. ```jsx import React from 'react'; import { WebChatCustomElement } from '@ibm-watson/assistant-web-chat-react'; import './App.css'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', hideCloseButton: false, showLauncher: true, }; function App() { return (

My Application

Main content area

); } export default App; ``` ```css /* App.css */ .custom-chat-position { position: fixed; left: 100px; top: 100px; width: 400px; height: 600px; z-index: 1000; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); border-radius: 8px; overflow: hidden; } /* Alternative: Position in bottom-right corner */ .custom-chat-position-corner { position: fixed; right: 20px; bottom: 20px; width: 350px; height: 500px; } ``` -------------------------------- ### Render Custom React Components in Chat Messages (React) Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Demonstrates how to use the `renderUserDefinedResponse` prop to render custom React components within chat messages. This feature utilizes React portals for each custom response type, allowing for rich UI elements like product cards and survey forms. It requires defining custom response types in the message data and handling them within the `renderUserDefinedResponse` function. ```jsx import React from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', }; // Custom React component for product cards function ProductCard({ product }) { return (
{product.name}

{product.name}

{product.description}

${product.price}

); } // Custom response for surveys function SurveyForm({ onSubmit }) { const [rating, setRating] = React.useState(0); const handleSubmit = () => { onSubmit(rating); }; return (

How satisfied are you?

{[1, 2, 3, 4, 5].map(num => ( ))}
); } function App() { const renderUserDefinedResponse = (event, instance) => { const { message } = event.data; // Handle product card responses if (message.user_defined?.type === 'product_card') { return ; } // Handle survey responses if (message.user_defined?.type === 'survey') { const handleSurveySubmit = (rating) => { instance.send({ input: { text: `User rated: ${rating}` }, context: { skills: { 'main skill': { user_defined: { rating } } } } }); }; return ; } // Default fallback return
Unknown response type
; }; return ( ); } export default App; ``` -------------------------------- ### Web Chat: Recreating Instance with Internal Config Object (React) Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Demonstrates a common pitfall where a config object is created inside a React component, causing the `WebChatContainer` to re-initialize on every render. Debugging is enabled to show the re-creation message. ```javascript import React, { 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); function App() { const [value, setValue] = useState(0); const config = { integrationID: 'XXX', region: 'XXX', serviceInstanceID: 'XXX', }; return (
); } export default App; ``` -------------------------------- ### Embed Web Chat Component in React App Source: https://context7.com/watson-developer-cloud/assistant-web-chat-react/llms.txt Demonstrates how to use the `WebChatContainer` component to embed the IBM watsonx Assistant web chat into a React application. It requires configuration options and optionally enables debug logging. ```jsx import React from 'react'; import { WebChatContainer, setEnableDebug } from '@ibm-watson/assistant-web-chat-react'; // Enable debug logging setEnableDebug(true); // Configuration must be memoized or defined outside component to prevent recreation const webChatOptions = { integrationID: 'your-integration-id', region: 'us-south', serviceInstanceID: 'your-service-instance-id', // subscriptionID: 'required-for-enterprise-plans', }; function App() { return (

My Application

); } export default App; ``` -------------------------------- ### Render Custom User Responses with React Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Demonstrates how to pass a `renderUserDefinedResponse` function as a render prop to the `WebChatContainer` component. This function is responsible for returning a React component to render custom content for user-defined messages. It highlights conditional rendering based on message properties and the importance of the `WebChatContainer` lifecycle. ```javascript import React from 'react'; import { WebChatContainer } from '@ibm-watson/assistant-web-chat-react'; const webChatOptions = { /* Web chat options */ }; function App() { return ; } function renderUserDefinedResponse(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
My custom content
} } ``` -------------------------------- ### Enable Debugging for Watson Assistant Web Chat Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Enables additional debug information output from the WebChatContainer component. This function should be called before rendering the component. It requires no input and provides no direct output, but affects the logging behavior of the web chat instance. ```javascript setEnableDebug(true); function App() { return ; } ``` -------------------------------- ### Web Chat: Preventing Re-creation with External Config Object (React) Source: https://github.com/watson-developer-cloud/assistant-web-chat-react/blob/main/README.md Presents a solution where the config object is defined outside the React component, thus preventing the `WebChatContainer` from re-initializing due to config changes on component re-renders. ```javascript import React, { useState } from 'react'; import { WebChatContainer, setEnableDebug } from '@ibm-watson/assistant-web-chat-react'; setEnableDebug(true); const config = { integrationID: 'XXX', region: 'XXX', serviceInstanceID: 'XXX', }; function App() { const [value, setValue] = useState(0); return (
); } export default App; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.