chenglou / react-radio-group

Better radio buttons.
MIT License
443 stars 75 forks source link

Automatic label assignment #33

Open jnsprnw opened 8 years ago

jnsprnw commented 8 years ago

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

danielberndt commented 8 years ago

Yes, you're right. This library is fairly low-level and it's debatable whether this is a good thing or not.

However it doesn't require too much effort to customise the functionality in user-land. So your case could be solved like this:

import {RadioGroup, Radio} from "react-radio-group";

export const MyRadioGroup = RadioGroup;
export class MyRadio extends React.Component {

  render() {
    const {children, ...rest} = this.props;
    return (
      <label>
        <Radio {...rest}/>
        {children}
      </label>
    );
  }
}

which then could be applied like this:

import {MyRadioGroup, MyRadio} from "./my-react-radio-group";

<MyRadioGroup name="fruit">
  <MyRadio value="orange">My Orange</MyRadio>
  <MyRadio value="apple">My Apple</MyRadio>
</MyRadioGroup>

It seems to me that this library provides enough flexibility to build something more opinionated on top of it without too much hassle. So I'm in favour of keeping it like it is. Maybe it's worth adding a section in the readme showcasing how to build something more opinionated on top of it.

Let me know what you think!

quantuminformation commented 7 years ago

good idea, and good answer!