Search code examples
javascriptreactjscheckboxradio-button

Setting state to be the value of the label of a radio button


I have a list of radio buttons that in a form.

<h6>Desired breed (if any)</h6>
            <div className="radio container-fluid">
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">Goldendoodle</p>
              </label>
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">English Goldendoodle</p>
              </label>
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">Labradoodle</p>
              </label>
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">Poodle</p>
              </label>
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">Other</p>
              </label>
              <label>
                <input
                  type="radio"
                  className="checkbox"
                  name="Breed"
                  onClick={(e) => setBreed(e.target.value)}
                />
                <p className="checkbox">No preference</p>
              </label>
             
            </div>
          </label>
        </div>

What I am trying to do is have the Breed variable set to the value of whatever checkbox is selected. The problem is I am getting on for the value instead of what the label says.

I cannot change the radio button's name attribute because I need only one to be selectable at a time. (I am open to other ways to accomplish this too).


Solution

  • try to change onClick like so:

    onClick={(e) => setBreed(e.target.nextSibling.textContent)}