React-React radio group v2.2.0: Better radio buttons.

icon
Latest Release: v2.2.0

'selectedValue' and 'onChange' are optional #22

Source code(tar.gz)
Source code(zip)

React-radio-group

npm install react-radio-group

Then either import {RadioGroup, Radio} from 'react-radio-group' or add node_modules/react-radio-group/umd/index.js into your HTML file (exports the RadioGroup global which contains both, the RadioGroup and Radio component.).

What This Solves

This is your average radio buttons group:

<form>
  <input type="radio" name="fruit" value="apple" />Apple
  <input type="radio" name="fruit" value="orange" />Orange
  <input type="radio" name="fruit" value="watermelon" />Watermelon
</form>

A few problems:

  • Repetitive fields (name, type, checked, onChange).
  • Hard to set the checked value. You need to put e.g. checked={'apple' === this.state.selectedFruitName} on every input.
  • Hard to retrieve the selected value.

Here's a better version (full example here)

<RadioGroup name="fruit" selectedValue={this.state.selectedValue} onChange={this.handleChange}>
  <Radio value="apple" />Apple
  <Radio value="orange" />Orange
  <Radio value="watermelon" />Watermelon
</RadioGroup>

Repetitive fields are either lifted onto the RadioGroup wrapper or already implicitly set on the Radio component, which is a simple wrapper around the radio input.

Formal API

<RadioGroup />

Exposes 5 optional props:

  • name: String: what you'd normally put on the radio inputs themselves.
  • selectedValue: String | Number | Boolean: the currently selected value. This will be used to compare against the values on the Radio components to select the right one.
  • onChange: Function: will be passed the newly selected value.
  • Component: String | React Component: defaults to "div", defines what tag or component is used for rendering the RadioGroup
  • children: Node: define your Radios and any other components. Each Radio component (a thin wrapper around input) within a RadioGroup will have some fields like type, name and checked prefilled.

<Radio />

Any prop you pass onto it will be transferred to the actual input under the hood. Radio components cannot be used outside a RadioGroup

License

MIT

Comments

  • Change documentation
    Change documentation

    Apr 30, 2018

    Plz change documentation, provide some way to make text around radio button clickable.

    For example

    <RadioGroup name="setting" selectedValue={1} onChange={null}>
              <label><Radio value="clickable" />You can click here to select</label>
              <Radio value="not" />you CANNOT click here to select
    </RadioGroup>
    
    Reply
  • get more then value in the handleChange func
    get more then value in the handleChange func

    Dec 9, 2018

    I have dynamically outputed radio groups, every group gets unique name. in the handleChange func I need get the name in addition to value. my state is a pair of { {groupName} : {selectedValue} } there's a way to get the name somehow?

    Reply
  • Move `prop-types` library to devDependencies
    Move `prop-types` library to devDependencies

    Jan 2, 2019

    As react and react-dom are already defined as devDependencies i propose to to the same with prop-types.

    Are there any cons?

    Reply
  • Adding code sandbox example
    Adding code sandbox example

    Jan 15, 2019

                                                                                                                                                                                                           
    Reply
  • Move prop-types to devDependencies
    Move prop-types to devDependencies

    Feb 27, 2019

    Implements proposal #54

    Reply
  • can this be used with useReducer?
    can this be used with useReducer?

    Jan 9, 2020

    I have switched my form to the useReducer methodology because it was getting too cumbersome. Now I'm not sure if it is possible to continue using this library or not.

    Here is my relavant code:

    const initialState = {
    	bagID: '',
    	lineTechName: '',
    	infoCorrect: '',
    	materialCorrect: '',
    	unwantedMaterials: '',
    	unwantedMaterial: '',
    	qualityAcceptable: '',
    	program: '',
    	sealingProperly: '',
    	temperature: ''
    };
    
    const [userInput, setUserInput] = useReducer(
    	(state, newState) => ({ ...state, ...newState }),
    	initialState
    );
    
    ....
    const handleChange = (evt) => {
    	const { name, value } = evt.target;
    	setUserInput({ [name]: value });
    };
    ....
    <RadioGroup
    	name={'infoCorrect'}
    	selectedValue={????}
    	// onChange={(value) => {
    		// 	setInfoCorrect(value);
    	// }}
    	onChange={handleChange}
    >
    <label className={'radio'}>
    	<Radio value={'yes'} />
    	Yes
    </label>
    <label className={'radio ml-5'}>
    	<Radio value={'no'} />
    	No
    </label>
    </RadioGroup>
    

    I added question marks to the biggest part that I'm unsure about. Also, I am guessing the handleChange logic will need to change because that is for normal text inputs.

    Reply
  • React warning about propTypes
    React warning about propTypes

    May 4, 2017

    Hi there, I've noticed that the latest version(3.0.1) published to npm is still using React.PropTypes even though the source code has been updated.

    I believe it's because the code is not build properly before publishing?

    Here you can check from the code compiled on npm is still referring to React.

    https://unpkg.com/[email protected]

    var _react = require('react');
    
    var _react2 = _interopRequireDefault(_react);
    
    var Radio = _react2['default'].createClass({
      displayName: 'Radio',
    
      contextTypes: {
        radioGroup: _react2['default'].PropTypes.object
      },
    
    
    Reply
  • Publish to NPM
    Publish to NPM

    Oct 27, 2014

    It would be nice to have this option

    Reply
  • Breaking the whole render function
    Breaking the whole render function

    Mar 27, 2016

    I am trying to render group of radio buttons using this component. This is what I wrote inside render():

          <div className="form-wrapper">
            {alert}
            <form onSubmit={this.handlePostAnswer}>
              <h3 className="question">{this.props.question.question}</h3>
              <div className="options-wrapper well" onClick={this.handleOptionChange}>
                <RadioGroup name="options" onChange={this.handleOptionChange}>
                  {Radio => (
                    <div className="radio">
                      <label>
                        <Radio value="radio1" /> Radio 1
                      </label>
                    </div>
                    <div className="radio">
                      <label>
                        <Radio value="radio2" /> Radio 2
                      </label>
                    </div>
                  )}
                </RadioGroup>
              </div>
              <button type="submit" className="btn btn-primary">Submit</button>
            </form>
          </div>
    

    This breaks the whole page, I mean it does not renders anything. The state and props are all fine - I checked. There is even no errors/warnings in logs.

    I have even tried rendering a simple radio button using this <Radio name="something" /> Some radio, even this breaks the whole render operation.

    Not sure what I am doing wrong, any help would be appreciated. Thanks.

    Reply
  • fix(README): add escapes to RadioGroup demo inputs
    fix(README): add escapes to RadioGroup demo inputs

    Jun 19, 2014

    When making sure that I wired everything up correctly, I grabbed the first illustration and saw the inputs as innerText. Obviously the actual demo you provide is correct.

    I just wanted to make sure anyone like me didn't run into the same issue.

    Reply
  • context based solution
    context based solution

    Jun 24, 2016

    This should be everything that is required to make a context based solution work.

    notes:

    • the readme still needs to be updated
    • due to the changes of how owner vs parent based context is treated, I had to update the peerDep of react from 0.13 to 0.14
    • <RadioGroup> will render a div containing its children by default, but the wrapper component can be modified via passing e.g. a comp="ul" prop
      this allows RadioGroup to have more than a single child node (see the example.jsx)

    All in all I find this solution much easier on the end user's side. Plus it fixes #12!

    Reply
  • Not wipe out DOM when changing values?
    Not wipe out DOM when changing values?

    Jul 10, 2015

    Firstly, great idea! Love it.

    However, when changing values, React completely wipes out the DOM inside the radio components. This is not ideal when wanting to animate the radio buttons after being checked etc.

    The best I could come up with (while still keeping the same pattern) was to use defaultChecked on the inputs instead of checked, and make shouldComponentUpdate inside the parent return false. Effectively making it an "uncontrolled" component.

    Feel free to close this issue as it's kinda solved — I was just wondering if you had any thoughts how this could be done a little cleaner?

    bug 
    Reply