chatscope / chat-ui-kit-react

Build your own chat UI with React components in few minutes. Chat UI Kit from chatscope is an open source UI toolkit for developing web chat applications.
https://chatscope.io
MIT License
1.34k stars 116 forks source link

Set message input value from another component #153

Closed jessica-lei-22 closed 5 months ago

jessica-lei-22 commented 6 months ago

Hello, I am trying to automatically set the message input value using a button. For example, instead of typing "Hi, how are you" directly into the message input, I should be able to click on my button and it will put that sentence into the input, and then I can edit it and/or hit "send". How can I achieve this since I can't access/change the value of the input?

supersnager commented 6 months ago

@jessica-lei-22 To acces to the input value, use the <MessageInput /> as a controlled component.

https://chatscope.io/storybook/react/?path=/docs/components-chatcontainer--docs#live-controlled-example

Here is a modified example from the link above. Please take a look at the line <InfoButton onClick={() => setMsgInputValue("Hi, how are you")}/>

const inputRef = useRef(null);
const [msgInputValue, setMsgInputValue] = useState("");
const [messages, setMessages] = useState([]);
const handleSend = message => {
  setMessages([...messages,{ message, direction: 'outgoing' }]);
  setMsgInputValue("");
  inputRef.current?.focus();
};

return (
  <ChatContainer style={ {  height: "500px"} }>
    <ConversationHeader>
      <Avatar src={kaiIco} name="Kai" />
      <ConversationHeader.Content userName="Kai" info="Active 10 mins ago" />
      <ConversationHeader.Actions>
        <InfoButton onClick={() => setMsgInputValue("Hi, how are you")}/>
      </ConversationHeader.Actions>
    </ConversationHeader>
    <MessageList scrollBehavior="smooth" typingIndicator={<TypingIndicator content="Emily is typing" />}>
      {messages.map( (m,i) => <Message key={i} model={m} /> )}
    </MessageList>
    <MessageInput placeholder="Type message here" onSend={handleSend} onChange={setMsgInputValue} value={msgInputValue} ref={inputRef} />
  </ChatContainer>
);