简体   繁体   中英

react hoc for checkbox and radio component

I'm building my own checkbox and radio component, so that I can reuse it over and over again.

It will be something like this

import React, { Component } from 'react'
export class Checkbox extends Component {
    render() {
        return (
            <input type={this.props.type === 'checkbox' ? 'checkbox' : 'radio'} placeholder={this.props.label} />
        )
    }
}

I can use it like this if I want a "checkbox" <Checkbox type="checkbox" label="My checkbox" />

I can use it like this if I want a "checkbox" <Checkbox type="radio" label="My checkbox" />

But how to improve above solution using HOC in this case? I got feedback of "create a higher order component that wraps the common component for each." from above implementation, does it even make sense to use HOC here? if HOC is a must requirement what will it looks like?

You don't need to create HOC. You're simply returning input element. But HOCs are used like mixin:

const NewComponent = (BaseComponent) => {
  // ... create new component from old one and update
  return UpdatedComponent
}

See this blog source to understand HOC better.


To improve your component a little better, you can do just like this:

import React, { Component } from 'react'
export class Checkbox extends Component {
    render() {
      const { type, label } = this.props
        return (
            <input type={type} placeholder={label} />
        )
    }
}

Now, you can simply pass type and label as required:

<Checkbox type="radio" label="The label" />
<Checkbox type="checkbox" label="The label" />

Or, if you want to use checkbox by default, then you can define the defaults like this:

Checkbox.defaultProps = {
  type: 'checkbox',
  label: 'The default label'
}

Now, if you use the component just like this:

<Checkbox />

This will render <input type="checkbox" label="The default label" /> .

For more information on default props, see the doc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM