Please see this codesandbox.
This codesandbox simulates a problem I am encountering in my production application.
I have an infinite scrolling table that includes checkboxes, and I need to manage the every-growing list of checkboxes and their state (checked vs non-checked). The checkboxes are rendered via vanilla functions (see getCheckbox) that render the React components. However, my checkboxes do not seem to be maintaining the parent state (called state in the code) and clicking a checkbox does not work. What do I need to do to make sure that clicking a checkbox updates state and that all of the checkboxes listen to state? Thanks! Code is also below:
index.js:
import ReactDOM from "react-dom";
import "@elastic/eui/dist/eui_theme_amsterdam_light.css";
import React, { useState, useEffect } from "react";
import { EuiCheckbox, htmlIdGenerator } from "@elastic/eui";
import { arrayRange, getState } from "./utils";
const Checkbox = ({ id, isChecked, onClick }) => (
<div style={{ margin: "1rem" }}>
<EuiCheckbox
id={htmlIdGenerator()()}
label={isChecked ? `${id} - On` : `${id} - Off`}
checked={isChecked}
onChange={() => onClick()}
/>
</div>
);
const getCheckbox = (props) => <Checkbox {...props} />;
const App = () => {
const [state, setState] = useState(getState(0, 1));
const [checkboxes, setCheckboxes] = useState([]);
const [addMoreCheckboxes, setAddMoreCheckboxes] = useState(true);
useEffect(() => {
if (addMoreCheckboxes) {
setAddMoreCheckboxes(false);
setTimeout(() => {
setState((prevState) => ({
...prevState,
...getState(checkboxes.length, checkboxes.length + 1)
}));
const finalCheckboxes = [...checkboxes].concat(
arrayRange(checkboxes.length, checkboxes.length + 1).map((id) =>
getCheckbox({
id,
isChecked: state[id],
onClick: () => handleClick(id)
})
)
);
setCheckboxes(finalCheckboxes);
setAddMoreCheckboxes(true);
}, 3000);
}
}, [addMoreCheckboxes]);
const handleClick = (id) =>
setState((prevState) => ({
...prevState,
[id]: !prevState[id]
}));
return <div style={{ margin: "5rem" }}>{checkboxes}</div>;
};
ReactDOM.render(<App />, document.getElementById("root"));
utils.js:
export const arrayRange = (start, end) =>
Array(end - start + 1)
.fill(null)
.map((_, index) => start + index);
export const getState = (start, end) => {
const state = {};
arrayRange(start, end).forEach((index) => {
state[index] = false;
});
return state;
};