I am using {message}
from the props in a component in the ReactJS.
The code is given below
import React from "react";
const MyMessage = ({ message }) => {
if (message?.attachments?.length > 0) {
return (
<img
src={message.attachments[0].file}
alt="message_attachment"
className="message-image"
style={{ float: "right" }}
/>
);
}
const msg = JSON.stringify(message);
console.log("fmsg = " msg.sender)
console.log("mes = " JSON.stringify(message))
console.log("now = " msg.first_name)
return (
<div
className="message"
style={{
float: "right",
marginRight: "18px",
color: "white",
backgroundColor: "#3B2A50",
}}
>
{message?.text}
</div>
);
};
export default MyMessage;
What I tried?
I used the following console stmts:
console.log(message); ->
[Object Object]
console.log(JSON.stringify(message));
{ "id":455890, "sender":{ "username":"GMmohit", "first_name":"Mohit", "last_name":"Maroliya", "avatar":"https://api-chat-engine-io.s3.amazonaws.com/avatars/potrait_rKDI2hb.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAZA5RH3EC2MM47GFP/20220213/ca-central-1/s3/aws4_request&X-Amz-Date=20220213T141431Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=1d5e0ec2418701210532824ba90af5f6366d17b7fa1f9dfadb6783cd8efdbfd6", "custom_json":"{}", "is_online":true }, "created":"2022-02-12 12:23:04.745937 00:00", "attachments":[], "sender_username":"undefined", "text":"----", "custom_json":"{}" }
const msg = JSON.stringify(message) console.log("now = " msg.first_name)
-> but it gives undefined
How can I access the values in {message}
like username
,first_name
etc? However, I am able to access message?.text
.
CodePudding user response:
It looks like your username and first name are coming off the sender object in your message. You'll need to consider the sender like:
message.sender.username
to access the username that is in the sender object in the message.
CodePudding user response:
If you are stringifying your json, you will not be able to take data from it, because it will serve as a whole string not as an object.