2

I am trying to default check the first radio button which the following code helps me to do. When loaded the page the first radio button is checked but the problem i am facing is that it doesn't allow me to check the other buttons that also are present in the array.

constructor(props: any) {
        super(props);
        this.state = {
            selectedSort: '',
            sort: ['Apple', 'Orange '],
        }
    }
this.state.sort.map((sortType:string, index:number) => {
     return <span key={`${sortType}${index}` onClick={() => this.setSort(sortType)} >
     <input type="radio" id={sortType} 
            value={this.state.selectedSort} 
           name={sortType} defaultChecked={index===0} 
           }/>
          <span>{sortType}</span>
                               
                                    })
 private setSort = (selectedSort: string) => {
        this.setState({
            selectedSort: selectedSort
        });
}
Mero
  • 51
  • 6
  • The `name` attribute should be the name of the radio button group, the `id` should be unique to a specific radio input. You are using the same value for both, so you've no groups. Can you provide a more complete component code example so we can see what the state is and how it's updated? – Drew Reese Jan 29 '21 at 07:37

1 Answers1

5

Issue

The defaultChecked value is a boolean but your condition sortType === 0 will always evaluate false since your sortType is only ever one of your sort state values, i.e. ["Apple", "Orange "].

Solution

If you want the first radio button to be default checked then you should compare against the mapped index.

defaultChecked={index === 0}

Other Issues & Suggestions

  1. Radio button group inputs should all have the same name attribute.
  2. Use a semantic label to wrap your inputs so they are more accessible.
  3. Use the radio input's onChange event callback versus an onClick, to update state.
  4. The sortType values alone should be sufficient for a React key.

Code:

{this.state.sort.map((sortType, index) => (
  <label key={sortType}>
    <input
      type="radio"
      id={sortType}
      value={selectedSort}
      name="sortType"
      defaultChecked={index === 0}
      onChange={(e) => this.setState({ selectedSort: e.target.id })}
    />
    {sortType}
  </label>
))}

Additionally, I suggest converting this to a fully controlled input since you have already all the parts for it. Remove the value attribute and use the checked prop. Set what you want the initial checked state to be. This will allow you have have already valid checked state.

state = {
  selectedSort: 'Apple',
  sort: ['Apple', 'Orange '],
}

{this.state.sort.map((sortType, index) => (
  <label key={sortType}>
    <input
      type="radio"
      id={sortType}
      name="sortType"
      checked={sortType === this.state.selectedSort}
      onChange={(e) => this.setState({ selectedSort: e.target.id })}
    />
    {sortType}
  </label>
))}

Demo

Edit how-do-i-default-check-a-radio-button-in-react

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • I am sorry i had tried it with two condition and have sort of mixed up the two. I tried first defaultChecked ={sortType ==="Apple"} and another was this defaultChecked={index === 0}. The problem i am facing is that it does not allow me to deselect the radio button for apple and select the radio button for the orange at all . – Mero Jan 29 '21 at 08:06
  • @Mero, See my #1 additional issue & suggestion, you need to fix the `name` attribute. Give all the inputs of the group the ***same*** `name` and they will handle deselecting when you choose another option. – Drew Reese Jan 29 '21 at 08:08
  • The value configuration does not really make sense. I'd recommend you remove the id attribute and set value={sortType} then set selectedSort: e.target.value – Nicholas_Jones Jan 29 '21 at 08:09