Home > Software engineering >  How to create radio button component in React
How to create radio button component in React

Time:09-21

I am trying to create a custom radio button in react. so my component is:

import React from "react";

export default function RadioBox(props) {
  const [isChecked, setChecked] = React.useState(false);

  const toggleCheck = (e) => {
    setChecked(e.target.checked || !isChecked);
  };

  return (
    <>
      <label className="radio-container">
        {props.text}
        <input
          type="radio"
          checked={isChecked}
          onChange={(e) => toggleCheck(e)}
          id={props.id}
          name={props.name}
        />
        <span className="checkmark"></span>
      </label>
    </>
  );
}

Apparently, in the parent component (SimpleBox), I want to use it, and later on according to that I am going to filter the products:

import React from "react";
import RadioBox from "../custom-components/RadioBox";

export default function SimpleBox() {
  return (
    <div className="simple-box card">
      <RadioBox text={"Price low to high"} name={"sorting"} />
      <RadioBox text={"Price high to low"} name={"sorting"} />
      <RadioBox text={"New to old"} name={"sorting"} />
      <RadioBox text={"Old to new"} name={"sorting"} />
    </div>
  );
}

But the buttons don't work properly. Sometimes I need to click several times to select or sometimes the other radio button is selected. Could you please have a look and help me to find the reason?

Thanks...

CodePudding user response:

Why aren't you simply using inputs?

  <form>
  <p>Please select your preferred contact method:</p>
  <div>
    <input type="radio" id="contactChoice1"
     name="contact" value="email">
    <label for="contactChoice1">Email</label>

    <input type="radio" id="contactChoice2"
     name="contact" value="phone">
    <label for="contactChoice2">Phone</label>

    <input type="radio" id="contactChoice3"
     name="contact" value="mail">
    <label for="contactChoice3">Mail</label>
  </div>
  <div>
    <button type="submit">Submit</button>
  </div>
</form>

CodePudding user response:

you have given each Radio the same Names. you have to give each one a different name. please try it

 <div className="simple-box card">
  <RadioBox text={"Price low to high"} name={"sorting"} />
  <RadioBox text={"Price high to low"} name={"sorting"} />
  <RadioBox text={"New to old"} name={"sorting"} />
  <RadioBox text={"Old to new"} name={"sorting"} />
</div>
  • Related