I am attempting to output a dollar figure within props.usdGain
to a web page using React. The thing that's tripping me up is that the line console.log("",props.usdGain);
succesfully puts the correct number into my console.
However, the line towards the bottom {"Net earnings $"+props.usdGain}
displays as undefined
.
A bizarre effect I'm seeing is that if I make any innocuous edit within my code editor (eg add a space or hit enter), the correct value suddenly appears on the screen. But then the moment I do a hard refresh on my browser, it goes straight back to undefined
.
Any ideas?
Ps Not sure if helpful, but this component is loaded via a function call with a JSX snippet in my App.js file.
import React from 'react';
import { Line } from 'react-chartjs-2';
const chart = (props) =>{
console.log("💲",props.usdGain);
return (
<div style={{height: "500px", width: "800px"}} key={props.vaultId}>
<Line data={props.chart} options={{
responsive: true,
title: {
text: props.vaultId,
display: true,
fontSize: 30
},
}}/>
<p style={{color:"gray", fontSize: "18px"}}>
{"Net earnings $"+props.usdGain}
</p>
</div>
)
}
export default chart;
It's a matter of how the JSX parser compiles data within curly braces. Under the hood, JSX is expecting expressions of a singular evaluation or datatype. For better comprehension, take the following as an example; when babel reads your JSX code to create a component, the below JS code is used:
React.createElement(component, props, ...children)
an example :
<MyButton color='blue' shadowSize={2} />
or frankly:
React.createElement(
MyButton,
{color: 'blue', shadowSize: 2},
'Click Me'
)
To break it down , the spread operator for accepting children can not be applied to your expression. See https://reactjs.org/docs/jsx-in-depth.html for more.
When I tried to reproduce your issue with multiple objects of any data type (ie: two separate strings or two variables) it returned undefined/failed loudly for me. Why it failed silently for you is most likely due to JSX reading your expression as a concatenation of two values therefore when it is mapped to the DOM, you just see undefined
.
As for your solution I recommend deconstructing {"Net earnings $"+props.usdGain}
as
{ `Net earnings $${ +props.usdGain }` }
String interpolation for the win.
Let me know if this works for you as an accepted solution.
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.