Closed theoshiao closed 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!
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!
I see. Dynamic imports are usually used in our NextJs projects. Happy to hear you solved the issue!
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:
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!