How to display function value in another component in react?

Viewed 513

I want to display the same time from my stopwatches formatTime in the other component so that when I save the value from the input and the current time from the stopwatch will save and show on the list? Can anyone help me I am new to react? The problem is that i don't know how to get the value from formatTime like i got it in Kello.js inside the return by just calling it because it is in a different component.

Kello.js

import React, {useState,useRef} from 'react';
    
const Kello = () => {
    const [timer,setTimer] = useState(0)
    const [isActive, setIsActive] = useState(false)
    const [isPaused, setIsPaused] = useState(false)
    const countRef = useRef(null)
    
    const handleStart = () => {
        setIsActive(true)
        setIsPaused(true)
        countRef.current = setInterval(() =>{
        setTimer((timer) => timer + 1)
        },1000)
    };

    const handlePause = () => {
        clearInterval(countRef.current)
        setIsPaused(false)
    };

    const handleResume = () => {
        setIsPaused(true)
        countRef.current = setInterval(() => {
        setTimer((timer) => timer + 1)
        },1000)
    };

    const handleReset = () => {
        clearInterval(countRef.current)
        setIsActive(false)
        setIsPaused(false)
        setTimer(0)
    };
    const formatTime = () => {
        const getSeconds = `0${(timer % 60)}`.slice(-2)
        const minutes = `${Math.floor(timer / 60)}`
        const getMinutes = `0${minutes % 60}`.slice(-2)
        const getHours = `0${Math.floor(timer / 3600)}`.slice(-2)

        return `${getHours} : ${getMinutes} : ${getSeconds}`
    };
    
    return (
        <div>     
        <div className='buttons'>
            {
                !isActive && !isPaused ?
                <button onClick={handleStart}>Start</button>
                : (
                    isPaused ? <button onClick={handlePause}>Pause</button> :
                    <button onClick={handleResume}>Resume</button>
                )
            }
            <button onClick={handleReset} disabled={!isActive}>Reset</button>
        </div>
        <p>{formatTime()}</p>
        </div>
    );
    
};
export default Kello; 

Tallennukset.js

import React, {useState} from 'react';
import ListanJasen from "./Jasen";
import {formatTime} from "./Kello";


const Tallennukset = () => {
    const [items,setItems] = useState([]);
    const [value, setValue] = useState("");
    
    
    const saveItem = () => {
        if(value === ''){
            return
        }
        setItems([...items, value]);
        setValue("");
    };
    const handleChange = (e) => {
        setValue(e.target.value);
    };
    return(
        <div>
            <input class="title" onChange={(e) => handleChange(e)} placeholder="Title"></input>
            <button class="tallennus" onClick={() => saveItem()}>Save</button>
            <button class="tyhjennys" onClick={() => setItems([])}>Clear list</button>

           
            <ul>
                {items.map((item, index) => {
                    return (
                    <div>
                    <ListanJasen key={index} item={item} /> 
                        
                    </div>
                    );
                })}
            </ul>
            
        </div>
    );
};

export default Tallennukset;

Jasen.js

import React from "react";


const ListanJasen = ({item}) => {
  return <li onClick={(e) => (e)}>{item}</li>;
};

export default ListanJasen;
1 Answers

the answer could be simple. Move your formatTime function to external file, like timeFormat.js and make it a common function e.g.:

    const formatTime = timer => {
        const getSeconds = `0${(timer % 60)}`.slice(-2)
        const minutes = `${Math.floor(timer / 60)}`
        const getMinutes = `0${minutes % 60}`.slice(-2)
        const getHours = `0${Math.floor(timer / 3600)}`.slice(-2)

        return `${getHours} : ${getMinutes} : ${getSeconds}`
    };

export default formatTime;

then import it where you need it, and use it anywhere.

Then you need to pass on your timer variable. Based on your project structure, you should either pass it with the props, e.g.

Kello.js

...
return(
 ...< Tallennukset timer={timer} />
);

then in Tallennukset.js:

import formatTime from './timeFormat.js';
...
const Tallennukset = (timer) => {
...
  <div> {formatTime(timer)} </div>
}

or pass it as a context from the top
or use state management library like redux to pass it around
there's many ways to share the variable with multiple components.

Related