Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
How to get value of desired textfield from map function of textfields?

These are differents posts with same textfields i.e comment with same useState I want to get the value of a desired textfield and other textfields should not get its value. Its like posts from facebook but I can't understand how to do it.

const PostTemplate = (props) => {
  const { data, user, MakeComment } = props;
  const [comment, setComment] = React.useState("");

  const HandleSubmit = (event) => {
    // event.preventDefault();
    //console.log(comment);
    console.log the value that gives the value of that particular textfield


  };

  return (
    <div>
       {data.map((item) => {
        return (
          <div className={classes.HomeCard} key={item._id}>
            <div className="card-image">
              <img src={item.photo} />
            </div>
            <div className="card-content">
              <h6>{item.title}</h6>
              <p>{item.body}</p>

              {item.comments.map((record) => {
                return (
                  <h6 key={record._id}>
                    <span style={{ fontWeight: "500" }}>
                      {record.postedBy.name}
                    </span>{" "}
                    {record.text}
                  </h6>
                );
              })}
              <TextField value={comment} onChange = {(e)=>setComment(e.target.value)} />
              <Button onClick={HandleSubmit}>Submit</Button>
            </div>
          </div>
        );
      })} 

          
        );
      })}
    </div>
  );
};
export default PostTemplate;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I've created a state for inputs which is an array of objects, each object has an id and text property, when one of the inputs changes we get its id and value in the CommentInputOnchange function and update the state, in that function, I find an object which has the same Id then update the text property and at the end I update the state

import { useState } from "react";

const data = [
  {
    _id: 1,
    photo: "",
    title: "title1",
    body: "body1",
    comments: [{ _id: 1, postedBy: { name: "a" }, text: "abc" }]
  },
  {
    _id: 2,
    photo: "",
    title: "title2",
    body: "body2",
    comments: []
  }
];

//Fill Comment Input State Based on Data, Push an object with id and text to that
const initialCommentInputValues = [];
data.forEach((d) => {
  initialCommentInputValues.push({ _id: d._id, text: "" });
});

export default function App() {
  const [commentInputValues, setCommentInputValues] = useState(
    initialCommentInputValues
  );

  const HandleSubmit = (event) => {};

  //each input send its id and value here and we change the state
  const commentInputOnChange = (id, value) => {
    console.log({ id, value });
    const newCommentInputValues = [...commentInputValues];
    const inputValue = newCommentInputValues.find((x) => x._id === id);
    inputValue.text = value;
    setCommentInputValues(newCommentInputValues);
  };

  return (
    <div>
      {data.map((item) => {
        return (
          <div key={item._id}>
            <div className="card-image">
              <img src={item.photo} />
            </div>
            <div className="card-content">
              <h6>{item.title}</h6>
              <p>{item.body}</p>

              {item.comments.map((record) => {
                return (
                  <h6 key={record._id}>
                    <span style={{ fontWeight: "500" }}>
                      {record.postedBy.name}
                    </span>{" "}
                    {record.text}
                  </h6>
                );
              })}
              <input
                value={commentInputValues.find((x) => x._id === item._id).text}
                onChange={(e) => commentInputOnChange(item._id, e.target.value)}
              ></input>
              <button onClick={HandleSubmit}>Submit</button>
            </div>
          </div>
        );
      })}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda