skip to Main Content

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


  1. To invoke the capitalize function inline of a JSX, you can use the curly braces {} to enclose the function.

    {capitalize("A test string")} //should work. 
    

    Read more about it here:
    https://react.dev/learn/javascript-in-jsx-with-curly-braces

    Login or Signup to reply.
  2. What you’re asking is simply… How to call a function in JavaScript.

    Take a look at what you have here:

    timerTypes.find(
        (type) => type.id === history.timer_type
    )?.timer_type.capitalize
    

    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 the Array type). And even if it was, you’re still not invoking that function (as you already do with the find 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:

    capitalize(timerTypes.find(
        (type) => type.id === history.timer_type
    )?.timer_type)
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search