I am currently building a countdown timer where a user inputs the time in minutes and can start and stop the clock. I am facing two errors,
I have made a state running when the clock is running and based on this state I am returning the buttons (either stop/ start), but I am getting the following error while using this function.
Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render.
The autostart prop of the react-Countdown component is not working in this case. (link for doc.
I have attached both codesandbox link and code also.
Here is the codesanbox link
My current code is
import React, { useState } from "react";
import Countdown from "react-countdown";
const Stopwatch = () => {
const [running, setRunning] = useState(true);
const [time, setTime] = useState(6);
const handleOnChange = (e) => {
console.log(e.target.value);
setTime(e.target.value);
};
function buttons(running) {
if(running ){
return (
<div>
<button style={{ marginTop: "15px" }} onClick={() => setRunning(false)}>
Stop
</button>
</div>
)
}
else {
return (
<div>
<button onClick={() => setRunning(true)}>Start</button>
</div>
);
}
}
console.log("time = " + time);
return (
<>
<div>
<label htmlFor="time"> Enter time in minutes </label>
<input
type="text"
id="time"
name="time"
value={time}
onChange={(e) => handleOnChange(e)}
/>
</div>
<div>
<h1>
<Countdown
date={Date.now() + { time } * 4000}
precision={3}
autoStart={running}
renderer={({ hours, minutes, seconds, completed }) => {
return (
<span>
{hours}:{minutes}:{seconds}
</span>
);
}}
/>
</h1>
</div>
{buttons}
</>
);
};
export default Stopwatch;
Please tell the error.
I had solved the first error by using the function inside DOM only like this:
import React, { useState } from "react";
import Countdown from "react-countdown";
const Stopwatch = () => {
const [running, setRunning] = useState(false);
const [time, setTime] = useState(6);
const handleOnChange = (e) => {
console.log(e.target.value);
setTime(e.target.value);
};
console.log("time = " + time);
return (
<>
<div>
<label htmlFor="time"> Enter time in minutes </label>
<input
type="text"
id="time"
name="time"
value={time}
onChange={(e) => handleOnChange(e)}
/>
</div>
<div>
<h1>
<Countdown
date={Date.now() + { time } * 4000}
precision={3}
autoStart={running}
renderer={({ hours, minutes, seconds, completed }) => {
return (
<span>
{hours}:{minutes}:{seconds}
</span>
);
}}
/>
</h1>
</div>
{running ? (
<div>
<button
style={{ marginTop: "15px" }}
onClick={() => setRunning(false)}
>
Stop
</button>
</div>
) : (
<div>
<button onClick={() => setRunning(true)}>Start</button>
</div>
)}
</>
);
};
export default Stopwatch;
But still, the autostart is not working, so after inputting the value in the text field and pressing start, the clock does not appear.