Home > OS >  how to add dynamic content inside a textarea tag using map method
how to add dynamic content inside a textarea tag using map method

Time:09-25

i am currently working on chat application with sockets , when i get different messages i use an array and then use map method to display them in simple html tags like p etc it worked perfect but inside text-area its not working i also tried to set text-area value property with map method but only i see is [object object] . also how can i automatically move the scroll bar down when messages there are more messages.

here is the code

import { Fragment, useEffect } from "react";
import { format } from "date-fns";
const Chat = ({ name, message }) => {
  const date = new Date();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();

  console.log("so bteay", message);
  return (
    <Fragment>
      <div>
        <h3 className="d-inline-block me-3"> Chat log </h3>
        {name && (
          <span className="me-3 d-inline-block">
            <div
              class="spinner-grow spinner-grow-sm text-success"
              style={{ fontSize: "10px" }}
              role="status"
            >
              <span class="visually-hidden">Loading...</span>
            </div>
          </span>
        )}
        <small className="text-muted d-block  "> {name}</small>
        <textarea
          cols="70"
          rows="8"
          value={message.map((eachMsg) => {
            return (
              <Fragment>
                {
                  <small className="text-muted d-inline-block">{`${hour}:${minute}:${second}`}</small>
                }
                <p
                  className="d-block shadow p-1 fw-bold rounded text-success"
                  style={{ fontFamily: "cursive" }}
                >
                  {eachMsg}
                </p>
              </Fragment>
            );
          })}
        ></textarea>
      </div>
    </Fragment>
  );
};

export default Chat;

CodePudding user response:

I think that you can't set html code inside textarea, unless you want to show it as a text?

CodePudding user response:

You can only pass 1 child ( text in this case ) to text area. But you are trying to pass an array. If what you meant to do is to have as many as textareas as your array, this is how you should go about it:

const texts = ["Hi", "Bye","done"];

<div>
      {texts.map((text) => (
        <textarea>text</textarea>
      ))}
</div>

but if you are trying to have 1 textarea with all your texts inside it, first you need to create a long string using join method, and then render that string.

  • Related