Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add new <p> tag every time user sends new message in ractJs?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading