How can I enable/disable checkboxes based on value of other checkboxes when data is coming from multidimensional array?
If any of the first tracks (pink) are checked, the first bus’s (pink) checkboxes should be enabled. OR If all of the first tracks (pink) are not checked, the first bus’s (pink) checkboxes should be disabled.
If any of the second tracks (purple) are checked, the second bus’s (purple) checkboxes should be enabled. OR If all of the second tracks (purple) are not checked, the second bus’s (purple) checkboxes should be disabled.
Here's a sandbox - https://stackblitz.com/edit/github-87m8g6?file=src/App.js
CodePudding user response:
you can use the random number generation along with date functionalities(avoiding duplicates)
Math.random() * new Date().getMilliseconds()
. check below
<ul className="flex">
{tracks.map((_, j) => {
return (
<li key={j} className="box">
{pair.map((active, i) => (
<div key={i} className="vertical flex">
<label
className="container"
htmlFor={Math.trunc(
Math.random() * new Date().getMilliseconds()
)}
>{`${i 1}`}</label>
<input
id={Math.trunc(
Math.random() * new Date().getMilliseconds()
)}
name={j}
type="checkbox"
onChange={saveChecked}
/>
<span className="checkmark"></span>
</div>
))}
</li>
);
})}
</ul>
i have fixed this. Please checkout below mentioned link.
https://codesandbox.io/s/unique-values-for-multi-dimentional-array-react-yzliem
CodePudding user response:
Some thing like this should do the work:
import React, { useState } from 'react';
function App() {
const tracks = new Array(4).fill(null);
const pair = [false, false];
const [activeBusses, setActiveBusses] = useState([[false, false],[false, false], [false, false], [false,false]]);
function saveChecked(e) {
const checked = e.currentTarget.checked;
const busIndex = e.currentTarget.id;
const trackIndex = e.currentTarget.name;
const updateActiveBuses = [...activeBusses];
updateActiveBuses[trackIndex][busIndex] = checked;
setActiveBusses(updateActiveBuses);
localStorage.setItem('activeBusses', JSON.stringify(updateActiveBuses));
}
return (
<main>
<h1>Track Send</h1>
<ul className="flex">
{tracks.map((_, j) => {
return (
<li key={j} className="box">
{pair.map((active, i) => (
<div key={i} className="vertical flex">
<label className="container" htmlFor={i}>{`${i 1}`}</label>
<input
id={i}
name={j}
type="checkbox"
onChange={saveChecked}
/>
<span className="checkmark"></span>
</div>
))}
</li>
);
})}
</ul>
<h1>Bus Recieve</h1>
<ul className="flex">
<li className="vertical box">
{[null, null, null, null].map((_, j) => (
<div key={j} className="flex">
<label className="container" htmlFor={j}>{`${j 1}`}</label>
<input id={j} type="checkbox" disabled checked={activeBusses[j][0] === true && activeBusses[j][1] === true}/>
<span className="checkmark"></span>
</div>
))}
</li>
</ul>
</main>
);
}
export default App;