7

I'm trying to use redux-form with react-semantic-ui and is having trouble with the Checkbox component. The Checkbox is not being checked. I've followed the example from the redux-form documentation, but no luck. Here's the Code snippet :

renderCheckBox = ({ input, label }) => {
  console.log(input.value);
  return (
    <Form.Field>
      <Checkbox
        label={label}
        checked={input.value ? true : false}
        onChange={input.onChange}
        />
    </Form.Field>
    );
};



<Field
  name="activated"
  label="Activate?"
  component={this.renderCheckBox}
/>

The output of console.log(input.value) is empty.

Oleksandr Fediashov
  • 3,967
  • 1
  • 20
  • 40
Tushar Khatiwada
  • 1,885
  • 2
  • 14
  • 24

2 Answers2

9

Reusable redux form checkbox with semantic ui

import React from 'react';
import { object } from 'prop-types';
import { Field } from 'redux-form/immutable';
import { Checkbox as CheckboxUI } from 'semantic-ui-react';

const Checkbox = ({
  input: { value, onChange, ...input },
  meta: { touched, error },
  ...rest
}) => (
  <div>
    <CheckboxUI
      {...input}
      {...rest}
      defaultChecked={!!value}
      onChange={(e, data) => onChange(data.checked)}
      type="checkbox"
    />
    {touched && error && <span>{error}</span>}
  </div>
);

Checkbox.propTypes = {
  input: object.isRequired,
  meta: object.isRequired
};

Checkbox.defaultProps = {
  input: null,
  meta: null
};

export default props => <Field {...props} component={Checkbox} />;

How to use?

import Checkbox from './Checkbox';

<form>
...
<Checkbox name="example" />
...
</form>
rofrol
  • 12,038
  • 7
  • 62
  • 63
Iurii Budnikov
  • 882
  • 7
  • 11
2

If you want to know whether the checkbox is checked or not, you have to use

onChange={(e, { checked }) => input.onChange(checked)}

instead of

onChange={input.onChange}

Here's a working example

QoP
  • 21,478
  • 16
  • 61
  • 69
  • Hi, The example isn't working here. It just displays `Loading`. – Tushar Khatiwada Jun 14 '17 at 06:30
  • Are you using IE or an obsolete web browser? You should be seeing something like [this](http://i.imgur.com/zfkRuAA.png) – QoP Jun 14 '17 at 06:35
  • I'm using latest version of Chrome. Now the form is showing too. I tried with your code too but the problem is same. I figured out that there's **hidden** class on the **input type="checkbox** and it has `z-index: -1`. I removed the `z-index` and now it's working as expected. But your's working without removing the **z-index** value. – Tushar Khatiwada Jun 14 '17 at 07:09
  • that `z-index:1` is supposed to be there in order to allow the custom component to work properly. I don't think that messing with the `z-index` is a good solution – QoP Jun 14 '17 at 07:27
  • But unfortunately the checkbox doesn't work unless I increase the **z-index** value to **3 or more**. – Tushar Khatiwada Jun 14 '17 at 07:55