In Redux Form, how can I set the initial value of the checked property of a checkbox?

Kevin

In our Redux Form 5.3 (not 6.x) app, I want to render an <input type="checkbox" /> like so:

// In some cases, fieldHelper.checked is initially undefined. Then, when the
// user clicks one of the checkboxes, fieldHelper.checked is
// explicitly set to true or false. This change from one of the component's
// props being undefined to having a value causes a React warning; see
// http://stackoverflow.com/a/38015169/473792 and
// https://facebook.github.io/react/docs/forms.html#controlled-components
// So to prevent that warning, we do a quick null check on
// fieldHelper.checked and replace it with false explicitly if it is
// undefined before rendering the checkbox.
const fieldHelper = this.props.field['checkbox'];
const checked = fieldHelper.checked || false;

const modifiedFieldHelper = Object.assign({}, fieldHelper);
delete modifiedFieldHelper.checked;

return (
  <input
    checked={checked}
    {...modifiedFieldHelper}
  />
);

}

As noted in the comment, in my testing environment, this.props.field['checkbox'].checked is undefined immediately after mounting the <input>. As a result, when my tests modify the value of this.props.field['checkbox'].checked, I get the following warning:

Warning: ApplicantForm is changing an uncontrolled input of type checkbox to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

... Unless I explicitly set the checked prop on the <input> to false instead of undefined, as demonstrated in the code snippet I posted above.

Instead of using this null check, I would like to set the initial value of this.props.fields['checkbox'].checked before my tests run. I know I can set the initial value of fields in Redux Form. Is there a way to set the initial value of an auxiliary property like the checked property that Redux Form also controls?

Santiago Bendavid

You could create a simple conditional in your checked attribute so that when the value is undefined you just return false:

<input 
  type="checkbox" 
  checked={typeof this.props.fields['checkbox'].checked == 'undefined'?false:this.props.fields['checkbox'].checked} 
  onClick={() => {... your onClick code ...}} />

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

how can i get sum of checkbox value and textbox value in another textbox when checkbox is checked or if checkbox unchecked remove the value

How I will set mat checkbox value(checked/unchecked) inside loop, based on API value in angular 8

How can i set another form field based on a checkbox?

How to set value variable from checkbox checked laravel?

How can I verify that an internal property was set with the correct value?

How can I use checkbox form in react?

How to set an initial value for @NSManaged property PFObject Subclass?

Test initial checked state of checkbox

How check if checkbox is checked? And how sum a value?

How can I set the value of a property on a class that I pass into another class?

How do I check if a checkbox is checked?

how can I set CSS for form validation

How to set property of radio button to checked

How can I Get the property by name from type and Set Propert value using reflection in C#

how can i check if checkbox is checked in datagridview column in vb.net

How to validate at least one checkbox is checked in a loop in Laravel form?

How to write a checked checkbox in form of tag-input

How to make an unchecked checkbox value 0 and checked value of 1?

checked for multiple checkbox in update form

How can I bind checkbox value and invoke a method on change?

CSS: How to set url image properly to checked checkbox

How can i set value to dropdown in flutter?

How to pass initial values to the FieldArray component in redux form?

how to set initial(default) value in dropdownButton?

How to set initial value of ForeignKey dynamically in CreateView?

How change value of checkbox checked using useState in React

How do i set null value to a property of a node in janusgraph?

Checkbox should be checked if the value is true

How to select all checkbox when i checked all check boxes

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo