skip to Main Content

I am building a simple password generator where the user clicks on a ‘submit’ button and is displayed a password based on which input checkboxes are ticked.

I currently have 4 pieces of state for each checkbox, and a simple input file that returns a simple input with a checkbox. I call this input file with each of their state as a prop as well as an event handler that they all use.

So i am currently stuck on how to see which input checkboxes are ticked and which are not… when i try to see this it is either they are all ticked, or they are all false (even when checkbox 1 and 2 are false and checkbox 3 and 4 are true).

I am a bit confused as to why this isnt working… any help?

Please let me know if you want me to provide some code to help better understand

2

Answers


  1. You can keep your state in an object, and update its values on change like:

    export default function App() {
      const [conditions, setConditions] = useState({
        a: false,
        b: false,
        c: false,
        d: false,
      });
    
      function handleChange(key) {
        setConditions((prev) => ({ ...prev, [key]: !prev[key] }));
      }
    
      function onSubmit(event) {
        event.preventDefault();
        generatePassword(conditions);
      }
    
      return (
        <form onSubmit={onSubmit}>
          {Object.entries(conditions).map(([key, value]) => (
            <label key={key}>
              {key}
              <input
                checked={conditions[key]}
                onChange={() => handleChange(key)}
                type="checkbox"
              />
            </label>
          ))}
          <button>Generate</button>
        </form>
      );
    }
    
    function generatePassword({ a, b, c, d }) {
      console.log("Generating password with the following params", { a, b, c, d });
    }
    
    
    Login or Signup to reply.
  2. Just store the 4 checkboxes in an object like below

        const [options, setOptions] = useState({
        lowercase: true,
        uppercase: true,
        numbers: true,
        specialChars: true,
      });
    

    and now wrtite an onChange function for handling clicks :

    const handleCheckboxChange = (event) => {
    const { name } = event.target;
    setOptions((prevOptions) => ({
      ...prevOptions,
      [name]: !prevOptions[name],
    }));
    

    };

    u can log the option state to see which checkboxes are checked. 🙂

    u can visit this link for more :
    https://dev.to/collegewap/how-to-work-with-checkboxes-in-react-44bc

    or look at this live demo.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search