lundi 13 janvier 2020

ReactJS: CSS3 Custom CheckBox values based on backend data

Here is Custom checkbox reactJS component,

import * as React from "react";
import styled from "../../styled-components";
import { Field } from "react-final-form";

interface Props<FieldValue = string, T extends HTMLElement = HTMLElement> {
  label: string;
  name: string;
  value?: FieldValue;
}

const Wrapper = styled.label`
  display: flex;
  ...

  input {
    position: absolute;
    ...
  }

  input[type="checkbox"]:checked + span:after {
    content: "";
    display: block;
    ...
  }

  input[type="checkbox"]:focus + span {
    ...
  }
`;

const Tickmark = styled.span`
  ...
`;

function Checkbox<FieldValue = string>({
  label,
  name,
  value
}: Props<FieldValue>) {
  return (
    <Wrapper>
      <Field<FieldValue>
        name={name}
        value={value}
        component="input"
        type="checkbox"
      />
      <Tickmark />
      {label}
    </Wrapper>
  );
}

export default Checkbox;

Multiple checkboxes are rendered by below given code snippet in another react component.

            data.records.map((record, i) => (
                <Checkbox
                  name="records"
                  label={record.label}
                  key={record.id}
                  value={record.id}
                />
            )) 

OnSubmit, all the checkboxes/values are stored in backend and then again while revisiting the same page, it should be fetched from backend and needs to be populated (checked) .

I added "checked" props in Checkbox, by default it checked ( - checkbox) and unable to uncheck it.

How to populate/check checkboxes based on values from Backend ? I'm wondering, there should some best practices to be followed to achieve this.

Thanks for your help, in advance.




Aucun commentaire:

Enregistrer un commentaire