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;