hi i have the code written in java-script and that is working fine, now for some of reason i need to convert that in react, i had searched about this in google but unfortunately didn't found any helpful things, here below is my code written in javascript
let message_pane = $(".msg_card_body");
let currentTime = formatAMPM(new Date());
message_pane.append(
"<div class='d-flex justify-content-start'>" +
"<div class='msg_cotainer'>" +
"<div class='msg_time'>You "+"<span>"+ currentTime +"</span>"+"</div>" +
"<div>"+text+"</div>" +
"</div>" +
"</div>");
Tried methods
Setting state:-
state = {
remoteStreams: [],
Message:'',
incomemsgs:[],
};
appending msg to state
let me = this;
// console.warn(text + 'received');
me.setState(
{
incomemsgs: {
text
}
})
rendering:-
{Object.keys(this.state.incomemsgs).map(key => {
let msgs = this.state.incomemsgs[key];
return (
<div
key={msgs}
/>
);
})}
but the above tried thing didn't worked, this may be dumb question but really i stuck here from long time, any helps or suggestions are heartly thank you.
if you are starting to use react, I would recommend you to go over its docs (specially this one https://reactjs.org/docs/thinking-in-react.html )
regarding to your problem. state.incomemsgs seems to be an array, but when updating your state you change it to an object instead of creating a new array and adding your new entry.
class MessageFeed extends React.Component {
state = {
incomemsgs:[]
}
onIncommingMessage(message) {
this.setState(prev => {
return {
...prev,
incomemsgs: [...prev.incomemsgs, message]
}
});
}
render() {
return (
<div>
{this.state.incomemsgs.map(entry => (
<div key={entry.id}>{entry.text}</div>
))}
</div>
)
}
}
Your append function adds the same group of elements every message. In that case this part
"<div class='d-flex justify-content-start'>" +
"<div class='msg_cotainer'>" +
"<div class='msg_time'>You "+"<span>"+ currentTime +"</span>"+"</div>" +
"<div>"+text+"</div>" +
"</div>" +
"</div>"
Can be converted into a React component.
import React from "react";
const MessageDisplay = props => {
return (
<div className="d-flex justify-content-start">
<div className="msg_cotainer">
<div className="msg_time">
You <span>{props.receiveTime}</span>
</div>
<div>{props.text}</div>
</div>
</div>
);
};
export default MessageDisplay;
Now this component can be rendered from an array of Message objects. I have created a codesandbox which simulates this
I set up some predefined messages in "messageBank" constant, which gets "recieved" on a 1 second interval within the useEffect to simulate recieving messages and updating the page through the map method.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.