I have a simple function to capitalize the first letter of timer_type,
the func is const capitalize = (string) => { return string.charAt(0).toUpperCase() + string.slice(1) }
In the render method of my app I have a long template string, the in the timerTypes.find method when there is a timer by type, I need the first letter to be uppercase. So need to invoke the capitalize. how would you invoke a function inline of a jsx?
<Box
sx={{
marginBlock: 3,
display: 'flex',
flexDirection: 'column',
}}
>
{timerHistory &&
timerHistory.map((history, index) => (
<Box key={index}>
<strong>
{`${
timerTypes.find(
(type) => type.id === history.timer_type
)?.timer_type.capitalize
} for ${toTime(history.duration_seconds)}`}
</strong>
{` on a ${Math.round(
history.goal_seconds / 60
)} minute timer ${age(history.created_at)}`}
</Box>
))}
</Box>
2
Answers
To invoke the capitalize function inline of a JSX, you can use the curly braces {} to enclose the function.
Read more about it here:
https://react.dev/learn/javascript-in-jsx-with-curly-braces
What you’re asking is simply… How to call a function in JavaScript.
Take a look at what you have here:
All you’re doing is simply appending the name of the function to a value somewhere. But your function isn’t defined as being a part of any given class or type (as opposed to the
find
function also used on this line of code, which is defined on theArray
type). And even if it was, you’re still not invoking that function (as you already do with thefind
function here).Your function is just a plain function. It is invoked directly and passed a value. So you would invoke it directly, and pass it a value:
For more practice and information on how to define and use functions in JavaScript, you are highly encouraged to start with some introductory tutorials on the JavaScript language. Building a React application is a fairly advanced topic as an introduction to the basic syntax and structure of the language itself.