Developers

Custom widgets

React & Preact

The React and Preact packages expose a single custom hook called useChat.

The following code snippet shows a few features easily implemented using this hook:

  • set up a controlled input field.
  • send a message when the enter key is pressed.
  • render text messages from both the user and the bot.
  • render a loading element when a bot response is expected to arrive.
1import { useChat } from "@nlxai/chat-react"; 2 3const CustomWidget = () => { 4 // Instantiate the chat with the same bot configuration as the off-the-shelf widget 5 const chat = useChat({ 6 botUrl: "", 7 headers: { 8 "nlx-api-key": "" 9 } 10 }); 11 12 return ( 13 <div> 14 {chat.responses.map((response, index) => { 15 if (response.type === "user" && response.payload.type === "text") { 16 return <div className="chat-bubble chat-bubble--user">{response.payload.text}</div>; 17 } 18 if (response.type === "bot") { 19 return response.payload.messages.map((message, messageIndex) => { 20 return <div className="chat-bubble chat-bubble--bot">{message.text}</div>; 21 }); 22 } 23 })} 24 {chat.waiting && <div>...</div>} 25 <input 26 value={chat.inputValue} 27 onInput={(event) => { 28 chat.setInputValue(event.target.value); 29 }} 30 /> 31 </div> 32 ); 33}