a blog for those who code

Sunday 2 September 2018

Create Radio Buttons Component in React

In this post we will be learning about creating Radio Buttons Components in React. In our previous post we learned about Components i.e. Components are small independent and resuable pieces of the UI which can be put together to create entire user interface. Think Components as a JavaScript function which takes an input and then return JSX which should be displayed on the screen.


Lets see a sample Component which displays "I am excited to Get Started with React" on the screen when called.

class Message extends React.Component {
  render() {
    return (
 <h1>I am excited to Get Started with React</h1>
    )
  }
}

We will be using the similar concepts and creating a small Radio Button Component for our application. It will look like below where the initial radio button will be selected as Option 1 and then when you select other option it will be firing an event. The values are dynamically sent to our component that means it can be any number of radio buttons.


For creating Radio Buttons we need two functions, one which will create our buttons and other which will detect any change in the radio button selection. We will also be keeping a state which will let us know that which is Radio Button is selected. So the initial code looks like below :

class RadioGroup extends React.Component{
  constructor(props){
    super(props);
    this.createRadioButton = this.createRadioButton.bind(this);
    this.radioItemChanged = this.radioItemChanged.bind(this);
    this.state = { selectedOption: '' }
  }
}

Lets start with creating Radio Buttons. In our component we will be attaching the radio buttons data as a prop. So that means all the data is available to us using this.props.radioItems, so if we have data then we will be looping through it and creating a single radio button using the function createRadioButton. To note, you need to give key value to each radio buttons otherwise you will get an error in console saying that your element is not unique. Also we will select the checked and unchecked option using the state object. We have also written an onchange event of input which will change the selectedOption of state.

renderRadioButtons(){
  if(this.props.radioItems){
    let radioButtons = this.props.radioItems;
    return radioButtons.map((radioButton) =>{
      if(radioButton != null){
        return this.createRadioButton(radioButton);
      }
    });
  }
}
createRadioButton(radioButton){
  return(<label className="radiobutton-container" key={radioButton.id}>
           {radioButton.text}
           <input type="radio" checked="checked" name="radio" 
              checked={this.state.selectedOption === radioButton.id} 
              onChange={()=>this.radioItemChanged(radioButton)} />
           <span className="checkmark-radio"></span>
         </label>
        );
}

Our next task is to handle the change event. As said earlier, whenever we change the input, we will change the state and add the selectedOption as the id of the radio button.

radioItemChanged(radioButton){
 console.log('Selected Option-------' + radioButton.id);
 this.setState({ selectedOption: radioButton.id});
}

Our task is almost complete, but one thing we have missed is that what will happen in the initial load. On the initial load, there should be one radio item to be selected. For that we will be using componentDidMount function, which is invoked immediately after a component is mounted. So this is best candidate to write our initial logic where we will select the first radio button as selected. As you can see, I am just setting the first id as a selectedOption which will make my first radio button as always selected on the initial load.

componentDidMount(){
  this.loadRadioButtons();
}
loadRadioButtons(){
  if(this.props.radioItems){
    this.setState({selectedOption: this.props.radioItems[0].id});
  }
}

Next is to know how to call the radio buttons. Calling is really simple where we have to pass an array of data as a prop to the component as shown below.

var data = [{id:1,text:"Option 1", value: "1"},
            {id:2,text:"Option 2", value: "2"},
            {id:3,text:"Option 3", value: "3"}];

ReactDOM.render(
  <RadioGroup type='RadioButtons' radioItems={data} keyVal='RadioButtons'/>,
  document.getElementById('react-container')
)

Full Code

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
    <style>
      .radio-items {
 padding: 4px 28px;
      }
      .radiobutton-container {
        display: block;
 position: relative;
 padding-left: 25px;
 padding-top: 2px;
 margin-bottom: 8px;
 cursor: pointer;
 font: 12px/16px Kievit;
 -webkit-user-select: none;
 -moz-user-select: none;
 -ms-user-select: none;
 user-select: none;
      }
     .radiobutton-container input {
       position: absolute;
       opacity: 0;
       cursor: pointer;
     }
     .checkmark-radio {
 position: absolute;
 top: 0;
 left: 0;
 height: 16px;
 width: 16px;
 background-color: #fff;
 border-radius: 50%;
 border: 1px solid #D2D2D2;
      }
      .radiobutton-container input:checked ~ .checkmark-radio {
  background-color: #faa234;
      }
      .checkmark-radio:after {
        content: "";
        position: absolute;
        display: none;
      }
      .radiobutton-container input:checked ~ .checkmark-radio:after {
        display: block;
       }
      .radiobutton-container .checkmark-radio:after {
         top: 5px;
         left: 5px;
         width: 6px;
         height: 6px;
         border-radius: 40%;
         background: white;
       }
      </style>
<script src="https://unpkg.com/react@16/umd/react.development.js" />
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" />
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js" />
      <title>Getting Started with React</title>
 </head>
 <body>
 <div id="react-container"></div>
 <script type="text/jsx">
    class RadioGroup extends React.Component{
      constructor(props){
        super(props);
        this.createRadioButton = this.createRadioButton.bind(this);
        this.radioItemChanged = this.radioItemChanged.bind(this);
        this.state = { selectedOption: '' }
     }
      componentDidMount(){
        this.loadRadioButtons();
     }
     loadRadioButtons(){
       if(this.props.radioItems){
         this.setState({selectedOption: this.props.radioItems[0].id});
       }
     }
     radioItemChanged(radioButton){
       console.log('Selected Option-------' + radioButton.id);
       this.setState({ selectedOption: radioButton.id});
     }
     renderRadioButtons(){
       if(this.props.radioItems){
         let radioButtons = this.props.radioItems;
         return radioButtons.map((radioButton) =>{
           if(radioButton != null){
             return this.createRadioButton(radioButton);
           }
         });
       }
     }
  createRadioButton(radioButton){
      return(<label className="radiobutton-container" key={radioButton.id}>
               {radioButton.text}
               <input type="radio" checked="checked" name="radio" 
                      checked={this.state.selectedOption === radioButton.id} 
                      onChange={()=>this.radioItemChanged(radioButton)} />
               <span className="checkmark-radio"></span>
             </label>
             );
  }
  render() {
       return <div key='radio-items' className="radio-items">
              {this.renderRadioButtons()}</div>;
   } 
}

var data = [{id:1,text:"Option 1", value: "1"},
            {id:2,text:"Option 2", value: "2"},
            {id:3,text:"Option 3", value: "3"}];

ReactDOM.render(
  <RadioGroup type='RadioButtons' radioItems={data} keyVal='RadioButtons'/>,
  document.getElementById('react-container')
)
</script>
</body>
</html>

I hope you have understood how to create a simple component in React, if youhave any doubt feel free to comment. Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment