Issue
I have a simple code that allows the user to enter minutes and seconds (website is written in react).
<div>
<span>
<input defaultValue="0" maxlength="2"/>
</span>
<span>m</span>
<span>
<input defaultValue="10" maxLength='2' />
</span>
<span>s</span>
</div>
But I would like to improve my functionality and that’s why I’m turning to you.
Currently the user can enter any number <= 99 (and in the seconds column he can enter 99) and any characters, but I would like the user to be able to enter a time of at least 5 seconds and at most 20 minutes.
Tell me how to limit the entered characters to numbers only and limit the maximum and minimum entered time.
Solution
You have to use an <input type="number" /> with the appropriate min and max.
To achieve the custom limitation, here's a proof of concept, keeping the time value (in seconds) inside a state and then transforming it into amounts of minutes and seconds for each input:
const { useState, useCallback } = React
const limitValue = (min, max, val) => Math.min(max, Math.max(min, val))
const App = () => {
const [value, setValue] = useState(10)
const onInput = useCallback(
(val, minutes) =>
setValue((prev) =>
limitValue(
5,
1200,
minutes ? val * 60 + (prev % 60) : ~~(prev / 60) * 60 + val
)
),
[]
)
return (
<div>
<span>
<input
type="number"
min={0}
max={20}
value={~~(value / 60)}
onInput={({ target: { value } }) => onInput(+value, true)}
/>
m
</span>
<span>
<input
type="number"
min={-1}
max={60}
value={value % 60}
onInput={({ target: { value } }) => onInput(+value)}
/>
s
</span>
<pre>
{JSON.stringify(
{
value,
minutes: ~~(value / 60),
seconds: value % 60
},
null,
2
)}
</pre>
</div>
)
}
ReactDOM.createRoot(root).render(<App />)
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<div id="root"></div>
Answered By - tao
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.