Unable to make the Checkbox work with redux-form and react-semantic-ui

Tushar Khatiwada picture Tushar Khatiwada · Jun 14, 2017 · Viewed 13.2k times · Source

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.

Answer

Iurii Budnikov picture Iurii Budnikov · Jun 23, 2017

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>