OvidijusParsiunas / deep-chat

Fully customizable AI chatbot component for your website
https://deepchat.dev
MIT License
1.26k stars 170 forks source link

Access Methods in React #167

Closed theoshiao closed 2 months ago

theoshiao commented 2 months ago

How do I access the submitUserMessage (or any other) method for DeepChat in React?

If I use the useRef hook to get the ref to the DeepChat component, it always returns null.

My code looks something like this:

const chatRef = useRef(null);
const askQuestion = (question) => {
        chatRef.current.submitUserMessage({ text: question }); //question will be randomly generated
}
...
<DeepChat
      ref={chatRef}
      demo={true}
      initialMessages={initialMessages}
      stream="true"
      style={{ borderRadius: '10px', height: '60vh', width: '80vw' }}
      messageStyles={styles.messageStyles}
      avatars={styles.avatars}
      submitButtonStyles={styles.submitButtonStyles}
/>

I have tried using forwardRef as well but it doesn't work either.

Do you have an example of using the methods in React?

Thanks!

OvidijusParsiunas commented 2 months ago

Hi @theoshiao.

I have attempted to replicate your code and everything appears to work fine for me. Here is the code I used, don't forget to remove the TypeScript syntax if you are using vanillaJS:

import {DeepChat as DeepChatI} from 'deep-chat-dev';
import { DeepChat } from "deep-chat-react-dev";
import React from 'react'

export default function App() {
  const chatRef = React.useRef<DeepChatI>(null);
  const askQuestion = (question: string) => {
    chatRef.current?.submitUserMessage({ text: question });
  }

  return (
    <div className="App">
      <DeepChat ref={chatRef} demo={true} />
      <button onClick={(event) => {askQuestion('hello');}}>Send Message</button>
    </div>
  );
}

If you are still experiencing problems, you can wrap DeepChat inside another element and reference that element. E.g:

import {DeepChat as DeepChatI} from 'deep-chat-dev';
import { DeepChat } from "deep-chat-react-dev";
import React from 'react'

export default function App() {
  const chatWrapperRef = React.useRef<HTMLDivElement>(null);
  const askQuestion = (question: string) => {
    (chatWrapperRef.current?.children[0] as DeepChatI)?.submitUserMessage({ text: question });
  }

  return (
    <div className="App">
      <div ref={chatWrapperRef}>
        <DeepChat demo={true} />
      </div>
      <button onClick={(event) => {askQuestion('hello');}}>Send Message</button>
    </div>
  );
}

Let me know if this helps you. Thanks!

theoshiao commented 2 months ago

Thanks! I previously was dynamically importing DeepChat like so:

const DeepChat = dynamic(() => import('deep-chat-react').then((mod) => mod.DeepChat), { ssr: false });

I switched to statically importing it and it works now. Thanks for the response!

OvidijusParsiunas commented 2 months ago

I see. Dynamic imports are usually used in our NextJs projects. Happy to hear you solved the issue!