I have have useState hook where I have array of 0's as follows const [binary, setBinary] = useState([0, 0, 0, 0, 0, 0, 0, 0]);
Then I have function called isToggled where I set the toggle to true and variable called bin that gets the binary value which is then sliced and concat and then set with the hook. I have so far it working a way that all the 0's will turn to 1's but won't go to zero when the checkbox is unchecked.
Then in the input fields onChange it is used as follows
<input type="checkbox" onChange={(e, b) => isToggled(0, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(1, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(2, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(3, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(4, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(5, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(6, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(7, b)} />
And in the text input field
<input
name="binary"
type="text"
value={binary}
onChange={binary.join("")}
/>
Whole code is as follows.
import React, { useState } from "react";
import "./App.css";
function Binary() {
const [binary, setBinary] = useState([0, 0, 0, 0, 0, 0, 0, 0]);
const [toggle, setToggle] = useState(false);
const [decimal, setDecimal] = useState(0);
const isToggled = (form) => {
setToggle(true);
let bin = binary
.slice(0, form)
.concat([toggle ? 1 : 0])
.concat(binary.slice(form + 1));
setBinary(bin);
};
const showDecimal = (e) => {
setDecimal("" + parseInt(binary.join(""), 2));
e.preventDefault();
};
return (
<div className="App">
<header className="App-header">
<form className={"form"}>
<div>
<input type="checkbox" onChange={(e, b) => isToggled(0, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(1, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(2, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(3, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(4, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(5, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(6, b)} />
<input type="checkbox" onChange={(e, b) => isToggled(7, b)} />
</div>
<div>
<input
name="binary"
type="text"
value={binary}
onChange={binary.join("")}
/>
</div>
<div>
<button onClick={showDecimal}>Convert</button>
</div>
<div>
<input type="text" value={decimal} />
</div>
</form>
</header>
</div>
);
}
export default Binary;