Saif Ali Khan
Saif Ali Khan

Reputation: 848

how to load radio buttons dynamically and use check property in react js?

I am trying to create a generic input field for radio button which i am gonna use in my project whenever i need radio button in reactjs so i want to know how to pass radio buttons dynamically so that the first element is checked by default and how to use the checked property in map function

render() {
    var self = this;
    return(
      <div>
      {
        self.props.options.map(function(option){
          return <label key={option[self.props.id]}><input type="radio" className={self.props.className}
          checked={?????} key={option[self.props.id]}
          onChange={self.props.onChange} value={option[self.props.name]} />{option[self.props.name]}</label>
        })
      }
      </div>
    );

  }

options is my array of objects which i am passing to the map function

Any help will be very helpful..

Thanks in advance :)

Upvotes: 7

Views: 18685

Answers (2)

Mayank Shukla
Mayank Shukla

Reputation: 104379

You need to use the state for this. Use this:

this.state={checked: 0}

onChange(i){
     this.setState({
         checked:index
     });
  }


render() {
    return(
        <div>
            {
                this.state.options.map((option,i)=>{
                    return <label key={option[this.props.id]}>
                                <input 
                                    type="radio" 
                                    className={this.props.className} 
                                    checked={this.state.checked == i? true: false}
                                    key={option[this.props.id]}
                                    onChange={this.onChange.bind(this,i)} 
                                    value={option[this.props.name]} />
                                {option[this.props.name]}
                            </label>
                })
            }
        </div>
    );
}

Check the working fiddle: https://jsfiddle.net/039eq8bx/

Upvotes: 6

naortor
naortor

Reputation: 2089

You can hold a state of checked index and init it to 0, and on your onchange function change it to the selected index.

something like :

<div>
{ self.state.options.map(function(option,i){
      return <label key={option[self.props.id]}>
                 <input type="radio" 
                        className={self.props.className}
                        checked={i==self.state.checkedIndex} 
                        key={option[self.props.id]}
                        onChange={self.onChange.bind(this,i)} 
                        value={option[self.props.name]} 
                 />
                 {option[self.props.name]}
             </label>
      })
}
</div>

and on your onchange function

onChange = function(i) {
     this.setState({checkedIndex : i})
}

Upvotes: 4

Related Questions