Search code examples
reactjsdebuggingradio-buttonreact-radio-buttons

Radio button not selecting value on the first click in react js


i created a custom radio button component i'm importing it and mapping it to an array. if i click on the radio button, it's not picking the value on the first click but after the second click it starts to pick the value

passing the name id value and checked through props

const CustomRadioButton = (props: any) => {
  const { label, id, name, onChange,isChecked } = props;
  return (
    <>
      <label htmlFor={id} className="customRadio">
        <input id={id} name={name} value={id} type="radio" checked={isChecked} onChange={onChange}/>
        <span className="label">{label}</span>
        <span className="checkmark"></span>
      </label>
    </>
  );
};

export default CustomRadioButton;

import CustomRadioButton from '../CustomRadioButton/CustomRadioButton';

const SortBy = () => {

  const [sortValue, setSortValue] = useState<String>('none')
  const sortByData = [
    {
      id: 'highest',
      name: 'sortBy',
      label: 'Highest to Lowest Time Per Question',
    },

    {
      id: 'lowest',
      name: 'sortBy',
      label: 'Lowest to Highest Time Per Question',
    },

    { id: 'questionType',
      name: 'sortBy', 
      label: 'Question Type' },

    {
      id: 'remark',
      name: 'sortBy',
      label: 'Correct | Incorrect | Unanswered',
    },
    {
      id: 'none',
      name: 'sortBy',
      label: 'None',
    },
  ];

  const handleOnchange = (e:React.ChangeEvent<HTMLInputElement> ) => {
    setSortValue(e.currentTarget.value)
    console.log(sortValue,"...")
  };

  let checked: any = '';
  return (
    <>
      <div className="SortBy">
        <h3 className="filtersTitle">SORT BY:</h3>
        {sortByData?.map((d: any, i: any) => {
          return (
            <div className="Radiochildren" key={i}>
              <CustomRadioButton
                label={d?.label}
                id={d?.id}
                name={d?.name}
                onChange={handleOnchange}
                isChecked={sortValue === d?.id}
              />
            </div>
          );
        })}
      </div>
    </>
  );
};

export default SortBy;

i tried setting preventdefault atill did'nt work


Solution

  • Your code works fine. The console log inside of handleOnchange is showing the old state because it's firing off before the component re-renders. If you move that console log outside of the handleOnchange function you will see the component is re-rendering with the correct value.

    Here is your code in a sandbox with an additional console log: https://codesandbox.io/s/react-typescript-forked-vgigdd?file=/src/App.tsx

    If you need access to that value within the handleOnchange function then just use e.target.value.