reactjsreact-final-form

How to use initialValues inside a Wizard with PrefixedField (React Final Form)?


I'm using React Final Form to create a multi-step wizard form.

I need to pass initialValues into my Wizard, which I can using the Field Component. However, I want to use PrefixedField instead, which provides a "prefix wrapper" to better structure my form data. Unfortunately, when I use PrefixedField, the initialValues props doesn't work.

<Wizard
  initialValues={{
     nomeCompleto: "Lois S",
   }}
   onSubmit={onSubmit}
   >
   <Wizard.Page>
      <FieldPrefix prefix="dadosCliente">
         <label htmlFor="nomeCompleto" className="form-label">
             Nome Completo
         </label>
          <PrefixedField
            name="nomeCompleto"
            className="form-control"
            component="input"
            type="text"
            placeholder="Nome Completo"
            validate={required}
            />
            <Error name="firstName" />

The code used for the PrefixedFields is exactly the same used on Prefixed Fields Example of React Final Form docs

/************ IMPORTANT CODE STARTS HERE **************/
const FieldPrefixContext = React.createContext();
const FieldPrefix = ({ prefix, children }) => (
  <FieldPrefixContext.Provider value={prefix}>
    {children}
  </FieldPrefixContext.Provider>
);
const PrefixedField = ({ name, ...props }) => (
  <FieldPrefixContext.Consumer>
    {prefix => <Field name={`${prefix}.${name}`} {...props} />}
  </FieldPrefixContext.Consumer>
);
/************* IMPORTANT CODE ENDS HERE ***************/

What am I doing wrong here or should I do it in another way? Thanks in advance.


Solution

  • Seems like I just needed to add the prefix to my initialValues.

    Working code:

    <Wizard
      initialValues={{
         dadosCliente:{
            nomeCompleto: "Lois S",
         }
       }}
       onSubmit={onSubmit}
       >
       <Wizard.Page>
          <FieldPrefix prefix="dadosCliente">
           <PrefixedField id="nomeCompleto" name="nomeCompleto" validate={required}>
              {({ input, meta }) => (
                <div>
                  <label htmlFor="nomeCompleto" className="form-label">
                    Nome Completo
                  </label>
                  <input
                    {...input}
                    type="text"
                    placeholder="Nome Completo"
                    component="input"
                    className="form-control"
                  />
                  {meta.error && meta.touched && (
                    <FieldError message={meta.error}></FieldError>
                  )}
                </div>
              )}
            </PrefixedField >
          ...