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;
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>
);
}