Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial values in Formik aren't showing

I have created a separate component in which it will render a card with form inside it. I used Formik API to handle it. This is my code.


function ParentComponent(){
    return (
        <View>
            <ChildComponent someDataFromApi={details}/>
        </View
    )
}

import { Formik } from "formik";
import * as Yup from "yup";

function ChildComponent(){
const someSchema={
    firstName: Yup.string().required().label("First Name"),
    lastName: Yup.string().required().label("Last Name"),
}
return (
   <Formik
       initialValues={first_name: details.first_name, last_name: details.last_name, }
       validationSchema={someSchema}
       onSubmit={(values) => console.log(values)}
   >
       <Field label={"First Name"} name="firstName">
       <Field label={"Last Name"} name="lastName">
   </Formik>
}

I don't know why it doesn't show the initialValues for the fields, I tried console logging it and it returns correct values means it already catches the data from initialValues, it just doesn't show it in the field.

like image 893
cptnalbrt Avatar asked Sep 16 '25 03:09

cptnalbrt


2 Answers

The initialValues are passed via the props as provided in the documentation. Here is a minimal working example.

import React from 'react';
import { Text, View, StyleSheet, SafeAreaView } from 'react-native';

import { Formik, Field } from "formik";

function ParentComponent() {
    return (
        <View>
            <ChildComponent someDataFromApi={{details: {
              first_name: "Hello",
              last_name: "World"
            }}}/>
        </View>
    )
}

function ChildComponent(props) {
    const details = props.someDataFromApi

   return <View>
        <Formik
            initialValues={details}
            onSubmit={() => {}}
        >
          {(props) => {
              return <View>
                <Field
                    value={props.values.details.first_name}
                />
              </View>
          }}
        </Formik>
      </View>
}


export default function App() {
  return (
    <View style={{margin: 20}}>
      <ParentComponent></ParentComponent>
    </View>
  );
}
like image 126
David Scholz Avatar answered Sep 19 '25 12:09

David Scholz


I think field names and initialValues parameter in your code should be the same.

enter image description here

like image 22
Ruslan Novikov Avatar answered Sep 19 '25 13:09

Ruslan Novikov