Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Components with 'Variants' in React - Conditional Rendering

pretty basic question here.

I am trying to begin learning React and I am curious about the best design pattern to go about this sort of thing.

I have a button component, and I want a 'primary' and 'secondary' variant of the component that apply a different class. Would the following be the best way to go about that? I am passing a 'variant' prop that defines which button to use.

If this isn't the best solution, what would be if I would like 'variants' for particular components.

Thanks!

class Button extends Component {

render() {

  // --- SECONDARY BUTTON --- //
  if(this.props.variant == 'secondary') {

    return (
      <div className = 'button-wrapper secondary'>
        <div className = 'button'>
          {this.props.text}
        </div>
      </div>
    );

  // --- PRIMARY BUTTON --- //
  }else if(this.props.variant == 'primary') {

    return (
      <div className = 'button-wrapper primary'>
        <div className = 'button'>
          {this.props.text}
        </div>
      </div>
    );
  }
}
}
like image 229
Mark Shull Avatar asked Mar 09 '26 07:03

Mark Shull


1 Answers

if your difference is only in the className, perhaps you can achieve the same by:

render() {
 const { variant } = this.props;
 return (
   <div className = {`button-wrapper ${ variant === 'secondary' ? '' : 'primary' }`}>
     <div className = 'button'>
       {this.props.text}
     </div>
   </div>
 );
like image 200
Jee Mok Avatar answered Mar 11 '26 07:03

Jee Mok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!