-2

I am creating a custom radio component using a functional component. I get the props to work and the css is working but I cannot see the actual 'radio button'.

please have a look at my code - what am I missing here.

type Props = {
  children: any,
  color?: string,
  size?: string,
}

const Radio = (props:Props) => {

  let radioClass = ''
    if(props.size === 'small') radioClass = 'radio-small';
    if(props.size === 'large') radioClass = 'radio-large';
    
    
    if(props.color === 'secondary') radioClass += ' radio-secondary';
    if(props.color === 'warning') radioClass += ' radio-warning';
    if(props.color === 'light') radioClass += ' radio-light';
    if(props.color === 'dark') radioClass += ' radio-dark';         

  return (
    <radio className={radioClass} > {props.children}</radio> 
  );
};

export default Radio
.radio-small  {
  font-size: 1.5em;
  
}


.radio-warning {
  color: red;
}
Fulano
  • 39
  • 1
  • 8

2 Answers2

1

There is no radio element in HTML. There's <input type="radio">. Also, input elements can't have children, so you probably wanted a label around this.

So it would be something like:

return (
    <label>
        {props.children}
        <input type="radio" className={radioClass} />
    </label>
);

Side note: You can do the radioClass thing more simply:

const {size, color} = this.props;

let radioClass = '';
if (size === 'small' || size === 'large') {
    radioClass += `radio-${size}`;
}

if (color === 'secondary' || color === 'warning' || color === 'light' || color === 'dark') {
    radioClass += ' radio-${color}`;
}

Or, if you know that props.size and props.color will always have valid values, simply:

const radioClass = `radio-${size} radio-${color}`;

...but your code seemed to be defending against size and color being absent or invalid. (I assumed that at least color was optional.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • what does the -$ mean? – Fulano Nov 11 '19 at 11:10
  • 1
    @Fulano `-$` doesn't mean anything, the dash is literal text. The substitution placeholders `${size}` and `${color}` within the template literals put the values of those variables there. ```radioClass += ` radio-${size}`;``` is equivalent to `radioClass += " radio-" + size;`. More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals – T.J. Crowder Nov 11 '19 at 11:16
1

you can do it like that

<input
  className={`radio-${props.size} radio-${props.color}`}
  type='radio'
/> 
  • This assumes that `size` and `color` are always valid. The OP's code appears to be defending against invalid values. (`size` might be required, but I assumed `color` was optional at least... Could be wrong.) – T.J. Crowder Nov 11 '19 at 11:17