Write code for a react component for a checkbox which toggles on the three states: true,…
- User
Write code for a react component for a checkbox which toggles on the three states: true, false and indeterminate.
Assistant
Below is an example of a React component for a checkbox that toggles between three states:
true,false, andindeterminate. Theindeterminatestate is visually represented by a dash or a line in the checkbox, indicating that the state is neither fully checked nor unchecked, often used for representing a mixed state (e.g., some but not all items in a group are selected).To achieve this, we'll use the
checkedandindeterminateattributes of the HTMLinputelement of typecheckbox. Note that theindeterminateproperty can be set programmatically but cannot be set directly through HTML attributes for user-initiated actions (it's more about the visual state reflecting the programmatic state). We'll manage the state with React'suseStatehook.jsximport React, { useState } from 'react'; const TriStateCheckbox = () => { // Enum for clarity on the states const States = Object.freeze({ TRUE: true, FALSE: false, INDETERMINATE: 'indeterminate' }); // Initialize with the indeterminate state for demonstration const [checkboxState, setCheckboxState] = useState(States.INDETERMINATE); const handleChange = () => { // Cycle through the states on each click: TRUE -> FALSE -> INDETERMINATE -> TRUE switch (checkboxState) { case States.TRUE: setCheckboxState(States.FALSE); break; case States.FALSE: setCheckboxState(States.INDETERMINATE); break; case States.INDETERMINATE: setCheckboxState(States.TRUE); break; default: console.error('Unhandled checkbox state:', checkboxState); } }; return ( <div> <input type="checkbox" // Set 'checked' to true only when state is TRUE checked={checkboxState === States.TRUE} // Set 'indeterminate' to true when state is INDETERMINATE indeterminate={checkboxState === States.INDETERMINATE} onChange={handleChange} /> <span> Toggle State (Now: {getStringState(checkboxState)}) </span> </div> ); }; // Helper function to display the current state as a string const getStringState = (state) => { switch (state) { case true: return 'TRUE'; case false: return 'FALSE'; case 'indeterminate': return 'INDETERMINATE'; default: return 'UNKNOWN'; } }; export default TriStateCheckbox;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.