Setting checked values in React Hooks Form (RHF)
posted 2022.07.04 by Clark Wilkins

For anyone else who finds aspects of RHF rather obscure, this is a helpful way to set1+ checkboxes in a set of N to default to being checked.

In this scenario, I have N mailing lists, and I want to be able to edit whether the contact C is on the list L.

First, I set an object which contains the results of a query to get all active lists (no dependence on connection to the contact C. I also get the current lists this contact is connected to as well.

const [availableLists, setAvailableLists] = useState();
const [currentLists, setCurrentLists] = useState();
[get the lists (we are inside useEffect here...)]
setAvailableLists( [database results] );
let theLists = [];

if ([0].rowCount ) Object.values([0].rows ).map( theList => { theLists.push( ) } );
setCurrentLists( theLists );

To create the entire set of checkboxes (using RHF and React Bootstrap) requires a loop (Object.values...) through all available lists, and setting checked if the list ID in this loop is in the array currentLists.

<Form.Group className="mb-3">

  <Form.Label muted>
    add to lists


    {Object.values( availableLists ).map( ( theList, key ) => {

      const {
        name: listName
      } = theList;
      return (

          checked={currentLists.includes( id )}
          { ...register( "lists", { onChange } ) }


    } ) }



Problem solved. Only lists where this contact is actually linked are checked.