Every time I hit Enter
It updates in the same tag
First I sent Hello World!
The second time I tried to send Hello as a new message It was updated with the same tag
I have only provided chunks of code which is being used for this send msg functionality
This the code I am also using speech to text which is why I have used setTranscriptValue to set speech value inside textarea
handleKeyDown
function is called onKeyUp in textarea
const [sendMsg, setSendMsg] = useState(<p></p>);
const handleKeyDown = (event) => {
console.log(event);
setTranscriptValue(event.target.value.trim());
if (event.key == 'Enter') {
handleSendKey();
setTranscriptValue('');
}
};
const handleSendKey = (event) => {
setSendMsg(<p> {transcriptValue} </p>);
};
<span id="send-btn" className='material-symbols-outlined' onClick={handleSendKey}> send </span>
<ul className="chatbot__box" id="ul-chatbot-box">
<li className="chatbot__chat incoming" id="li-incoming-msg">
<span className="material-symbols-outlined">
smart_toy
</span>
<p>Hi there, How can I help you today?</p>
</li>
<div
id="div-btn-res"
className="btn"
style={{ display: 'none' }}
></div>
<li className="chatbot__chat outgoing"> {sendMsg} </li>
</ul>
>Solution :
If you want to grow a list of messages, you should maintain an array instead of a single element.
It’s also not recommended to store JSX elements in state. Store data only and leave the rendering to the component.
const [sendMsg, setSendMsg] = useState([]); // init with an empty array
const handleSendKey = (event) => {
setSendMsg((msgs) => [...msgs, transcriptValue]); // add to the array
};
Then in your render / return value, map over the values
{sendMsg.map((msg, i) => (
<li className="chatbot__chat outgoing" key={i}>
<p>{msg}</p>
</li>
))}