This seems to be very silly to me but I am having this problem. Can anybody help me with this. So, I have an API that I am fetching some data and seems that the API response has a data format like this:
start-time:2323232
end-time:2332323
Now, when in my react rendering component, I am trying to display the data like this:
{data.start-time}
I am actually getting an error saying that time is undefined. Are there any rules that we cannot read/display data in JSX with - separator or something like that. Or, Does anybody know how can I solve that problem. Any helps would be highly appreciated.
CodePudding user response:
You cannot use start-time
as an identifier. you need to use square brackets to access the property in this case
data["start-time"]
For further reference Object property accessors
CodePudding user response:
You can only use the dot notation if the property name is a valid JavaScript identifier.
In JavaScript, identifiers are case-sensitive and can contain Unicode letters,
$
,_
, and digits (0-9), but may not start with a digit.
Properties that are not valid identifiers must be accessed through the bracket notation.
const data = { name: "stopwatch", "start-time": 2323232, "end-time": 2332323 };
console.log(data.name); // <- valid identifier
console.log(data["start-time"]); // <- invalid identifier