Home > OS >  How to render time function results in component?
How to render time function results in component?

Time:08-22

I have a component that formats the date and returns a timestamp. Currently the date is working but I cannot render the readableTime function in a Results component. You will see the state is setup as a condition to render the Results component which should hold the readableTime function. I can return text "working", but not the function. Any help appreciated.

import React, { useEffect, useState } from 'react';
import ReactTooltip from 'react-tooltip';

const DatetimeCell = (props) => {
    const [showReadableTime, setShowReadableTime] = useState(false);

    const readableTime = (timestamp) => {
        const time = new Date(timestamp);
        const timeOptions = {
            hour: 'numeric',
            minute: 'numeric',
            hour12: true
        };
        const rTime = new Intl.DateTimeFormat('en-US', timeOptions).format(time);
        return rTime;
    }

    const dateFormat = (timestamp) => {
        const date = new Date(timestamp);

        return (date.getMonth()   1)  
            "/"   date.getDate()  
            "/"   date.getFullYear();
    }

    useEffect(() => {
        setShowReadableTime(true);
    }, []);

    const Results = () => (
        <span> working{readableTime}</span>
    )

    const tooltipOptions = {
        text: props.text,
        tooltip: props.tooltip,
        tooltipPlacement: props.tooltipPlacement
    };

    return (
        <>
            <ReactTooltip />
                <td data-tip={dateFormat(tooltipOptions.tooltip)} data-place={tooltipOptions.tooltipPlacement || 'right'}>
                    {dateFormat(tooltipOptions.text)}
                    { showReadableTime ? <Results /> : null }
                </td>
        </>
    )
};

export default DatetimeCell;

CodePudding user response:

Your readableTime is a function that accepts timestamp as a parameter. Your rest of the code doesn't seem to indicate where the timestamp would come from, so I assume you'll pass it as a literal value when you're calling it, like so:

const Results = () => (
    <span> working {readableTime(1661146119165)}</span>
)

If by any chance you want to output the current time as default, you could update your function signature to have a default value for timestamp, like so:

const readableTime = (timestamp = Date.now()) => {...}

Or you could handle the missing parameter inside the function definition.

const readableTime = (timestamp) => {
    if (!timestamp) {
        timestamp = Date.now();
    }
    ...
}

Now you could call the function without the timestamp parameter as well.

const Results = () => (
    <span> working {readableTime(1661146119165)}</span>
)
  • Related