Cassidy
Cassidy

Reputation: 3408

Reusable React checkbox component with image without ID

I'm trying to make a reusable React component for a checkbox.

Now, I know what a standard image-replacement for a checkbox looks like, so here it is in my React project:

import React, { Component } from 'react';

class Checkbox extends Component {
  render() {
    return (
      <div className="checkbox">
        <input type="checkbox" name="thing" value="valuable" id="thing"/><label for="thing"></label> {this.props.text}
      </div>
    );
  }
}

export default Checkbox;

And here's the general CSS:

input[type=checkbox] {
  display:none;
}

input[type=checkbox] + label {
  background: url("checked.png") no-repeat;
  background-size: 100%;
  height: 20px;
  width: 20px;
  display: inline-block;
  padding: 0;
}
input[type=checkbox]:checked + label {
  background: url("unchecked.png") no-repeat;
  background-size: 100%;
  height: 20px;
  width: 20px;
  display: inline-block;
  padding: 0;
}

Now, because this is React, I want to be able to reuse this component. But, I can't reuse an ID. What should I do to make a checkbox with an image replacing the native checkbox? Is there a way to do this without this "label" method? I'd prefer to not use a random number as the ID, or something along those lines.

Upvotes: 1

Views: 4820

Answers (2)

Alan Draper
Alan Draper

Reputation: 397

my way to do this is usually to do something like this:

<div className="checkbox">
   <label><input type="checkbox" value="valuable" /> <span>{this.props.text}</span></label>
</div>

Upvotes: 0

Andy_D
Andy_D

Reputation: 4228

Pass the id as a prop to the component when you instantiate it.

<Checkbox id="whatever" value={state.valueOrWhatever} text="Change The Value!" />

in your component (note for in JSX is htmlFor):

<input type="checkbox" name={this.props.id} value={this.props.value} id={this.props.id} /> <label htmlFor={this.props.id}></label> {this.props.text}

Upvotes: 1

Related Questions