import React, {useState} from 'react';
const Checkbox = props => (
<input type="checkbox" {...props} />
)
const GenerateProgramClasses = (props) => {
const [checkBoxes, setCheckBoxes] = useState({default:false})
const listOfClasses =
Object.keys(props.classesDB).map(
class =>
<li key={props.areaOfStudy+'_'+ class}>
<Checkbox
checked = //{ some function that picks true or false, and I got a lot of errors/warnings }
onChange = //{
(e)=> // Calls some handler function that would take e.target.checked
// and store it with a key into a useState({default:false}) object,
// the default is there because when the page gets rendered for the
// first time all checkboxes should be unchecked.
}
onClick={(e)=> props.sumCredits(e, props.classesDB[class])}
/>
{props.areaOfStudy + ": " + class + ""}
Credits: {props.classesDB[class]}
</li>
)
return(
<div>
<p>Step: {props.pageNum}</p>
<h2>Program Core: {props.areaOfStudy}</h2>
<h3>Total Credits: {props.credit}</h3>
<form>
<ol>
{listOfClasses}
</ol>
</form>
<button onClick={() => props.previousPage()}>previous</button>
<button onClick={() => props.nextPage()}>next</button>
</div>
)
}
export default GenerateProgramClasses
The above is my code which would generate a page containing a list of check boxes for school courses and its corresponding credits. When I tick the check box sumCredits would run, then add/subtract the credits from a total credit variable. Finally, when I click on my next/previous button, the state for pageNum would change, because I have a switch statement from App.js this would trigger the correct page to be rendered using GenerateProgramClasses component again.
Everything works great when I click on my forward buttons. However, because I am re-rendering the page every time I click on a button, all my previous history for those checked boxes would disappear. I have tried to fix this by creating a new state that would keep track of which checkbox was clicked on, and then use that key value pair to rebuild the list of checkboxes. This did not work at all, for some reason react would check all the boxes true or false at the same time for all the boxes. This happened to me before when I didn't add the unique key values to my list elements. I am not positive if this is actually what's causing it.
So how do you tell reactJs that when a checkbox is checked remember its state so next time you re-render the page use those previous state as arguments to rebuild the list of checkboxes again? I have fix this otherwise my total credit counter calculation would get screwed up.Thanks.