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 ( results.data[0].rowCount ) Object.values( results.data[0].rows ).map( theList => { theLists.push( theList.id ) } );
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
  </Form.Label>

  <div>

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

      const {
        id,
        name: listName
      } = theList;
      return (

        <Form.Check>
          label={listName}
          checked={currentLists.includes( id )}
          key={key}
          type="checkbox"
          value={id}
          inline
          { ...register( "lists", { onChange } ) }
        />

      );

    } ) }

    </div>

</Form.Group>

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