Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created June 17, 2022 10:58
Show Gist options
  • Save nexpr/f591ae324920837b047cf9a560186a82 to your computer and use it in GitHub Desktop.
Save nexpr/f591ae324920837b047cf9a560186a82 to your computer and use it in GitHub Desktop.
hex input react component
import { useState } from "react"
import { render } from "react-dom"
import HexInput from "./HexInput.js"
const App = () => {
const [num, setNum] = useState(0)
return (
<div>
<HexInput value={num} onChange={(value => setNum(value))} />
<div>{num}</div>
</div>
)
}
render(
<App/>,
document.getElementById("root")
)
import { useState } from "react"
const toHexString = (num) => {
return num.toString(16).toUpperCase()
}
const fromHexString = (hex) => {
return hex ? parseInt(hex, 16) : 0
}
const format = (dirty_hex) => {
return dirty_hex.toUpperCase().replace(/[^0-9A-F]/g, "")
}
const HexInput = ({ value, defaultValue, onChange, ...props }) => {
const [state, setState] = useState(defaultValue ?? 0)
const input_value = toHexString(value ?? state)
const inputOnChange = (event) => {
const num = fromHexString(format(event.target.value))
if (onChange) {
onChange(num)
} else {
setState(num)
}
}
return <input {...props} type="text" value={input_value} onChange={inputOnChange} />
}
export default HexInput
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment