GithubHelp home page GithubHelp logo

react-radio-group's Introduction

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

react-radio-group's People

Contributors

audiolion avatar briandamaged avatar chantastic avatar chenglou avatar danielberndt avatar dumptruckman avatar hawkrives avatar koulmomo avatar nitinhayaran avatar nkbt avatar ziad-saab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-radio-group's Issues

why wrap component with `div`?

The render method for the radio group returns a div:

render: function() {
  let {name, selectedValue, onChange, children} = this.props;
  return (
    <div>
      {children && children(radio(name, selectedValue, onChange))}
    </div>
  );
}

But if the children function can only return one value, which is assumed to be an element, then why the need to wrap everything in a <div>?

I think it can just return calling the children:

render: function() {
  let {name, selectedValue, onChange, children} = this.props;
  return children ? children(radio(name, selectedValue, onChange)) : null;
}

Indicate selection as required?

Great component!
Was just thinking it would be cool to maybe include some way of duplicating the 'required' functionality within a static HTML5 form? The bare minimum is one of the radio inputs within a namespace/group having the attribute but it is suggested they all have it just just for consistency.
This can be currently achieved by adding the required attribute to the <Radio> children nodes, however it would be nice to specify it on the RadioGroup to match all the other API props?

Happy to look into this and create a PR if you agree?

Tab index issues

Component seems to interrupt the tab index order of the from it is used in.

Please support React 0.14

I think you just need to change the dependency information in package.json.

I wouldn't post this issue, but the peerDependency is preventing me from using it with 0.14.

Thank you.

Question:

Hey,

Curious why are wrapping this in a function and then returning React.createClass. Do you mind explaining why I'd want to do that?

Thank you,
Peter

function radio(name, selectedValue, onChange) {
  return React.createClass({
    render: function() {
      return (
        <input
          {...this.props}
          type="radio"
          name={name}
          checked={this.props.value === selectedValue}
          onChange={onChange.bind(null, this.props.value)} />
      );
    }
  });
}

`displayName` in published NPM version is "index" which causes misleading error messages

I saw this error in my project:

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of index. See https://fb.me/react-warning-keys for more information.

Breakpointing and tracing up the stack I found out it was from react-radio-group; the build I have from npm (2.1.1) has this snippet:

module.exports = _React['default'].createClass({
  displayName: 'index',

Breaking the whole render function

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.

Allow setting className?

Currently RadioGroups are turned into divs with no classNames

Setting className on RadioGroup is ignored

Suggest allowing className to be passed through to the div?

And perhaps allow setting component too (sometimes a fieldset would make sense instead of a div)

edit: I'm an idiot, sorry sorry sorry

Make onChange handler optional

If I do no specify an onChange handler, for e.g.

 <RadioGroup ref="deliverymethod" name="deliverymethod">
...
</RadioGroup>

I get an error:

Uncaught TypeError: Cannot read property 'bind' of undefined

Does the onChangeHandler need to be set. Can’t the React element maintain its own state, and update it when the value changes.

New release

Could we have a new release please? I don't want to set an onChange method and noops make me unhappy :(

Not wipe out DOM when changing values?

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?

React warning about propTypes

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
  },

Id required somewhere

Hello,

I'm using the component on a table in order to filter the table according to the radio that is selected. So far so good. That works no worries.

Now, when I render 3 of these tables in different tabs, then the radio that is selected is only for the radio in the last tab and then doesn't change.

I believe this happens because the values are the same in all 3 tabs (namely: 0, 1, 2) and therefore the component doesn't know which to select.

Would it be possible to have an identifier for the specific RadioGroup (or is there one that I missed?) so that we can use it to select specific radios. Or all for that matter.

thanks

Change documentation

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>

Screen reader support is lacking.

Please consider making this library better for people with disabilities. I have opened a PR (#47) that will make the very simple changes required to make this widget WAI-ARIA 1.1 compliant.

Automatic label assignment

Currently the label-tag needs to be wrapped around the Radio-tag within the JSX-code. I think it would be preferable if one would to have the label-tag separated (and not wrapped around) and without the need to be written.
The output would be:

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

from this JSX-input:

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

It would be great if the for-attribute would be generated automatically from the value-prop.

I know, the placement of the label-tag is debatable but one benefit would be that you don’t need to include the label-tag in the code like in the example:

<label>
  <Radio value="apple" />Apple
</label>

See https://www.w3.org/TR/WCAG20-TECHS/H44.html#H44-examples

get more then value in the handleChange func

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?

not bug, just ask a question?

const {Component, name, selectedValue, onChange, children, ...rest} = this.props;
In this Line, name、onChange、selectedValue are not be used in render function, the purpose just get the exact rest props?

Tests?

Any plans to add tests? if not I can add some.

New library?

Due to the nature of things there's no way to emulate a controlled component a-la-React. Might have to roll one's own custom radioButton implementation... But this library still works fine.

Provide label element linked to input

Hi,
Great component, however I'm missing functionality to provide label with for attribute that would link to input element. Would it be possible to include this property?

can this be used with useReducer?

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.

Iterate through array to get radio values

Hello. I am trying to iterate through an array to get the values for the Radio components. However, I'm having issues:

renderRadios(options){
    let radioItems = [];
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      radioItems.push( <Radio value={option.value} label={option.label} /> )
    }
    return radioItems;
}
render() {
  return (
    <div>
      <h1>&x-{this.props.parameterData.param}={this.props.parameterData.default}</h1>
      <RadioGroup
        name={this.props.parameterData.param}
        selectedValue={this.state.selectedValue}
        onChange={this.handleChange}>
        {Radio => (
          <div>
            {Object.keys(this.props.options).map(this.renderRadios)}
          </div>
        )}
     </RadioGroup>
   </div>
  );
}

Since Radio is not defined, I am getting an error. If I put the loop right in the Radio => function, I get syntax errors. How can I accomplish this?

I've made a JSFiddle here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.