Issue with Formik compatibility in Next JS 14 Application Structure

I attempted to create a basic validation form using Formik. I meticulously followed their tutorial and example, but unfortunately, the form is not functioning correctly. Despite my efforts, I have been unable to identify a solution (Please correct me if I'm mistaken). Below is the error message I encountered:

https://i.sstatic.net/aZPrO.png

package.json

{
  "name": "simple-form",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "formik": "^2.4.5",
    "next": "14.1.0",
    "react": "^18",
    "react-dom": "^18",
    "yup": "^1.3.3"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "14.1.0",
    "typescript": "^5"
  }
}

Formik Code

"use client";

import {Formik} from "formik";

interface MyFormValues {
    email: string;
    password: string;
}

export default function HomePage() {
    const initialValues: MyFormValues = { email: "", password: "" };

    return (
        <Formik
            initialValues={initialValues}
            onSubmit={(values) => console.log(values)}
        >
            {({ handleSubmit, handleChange, handleBlur, values }) => (
                <form onSubmit={handleSubmit}>
                    <input
                        type="email"
                        name = "email"
                        placeholder = "email"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.email}
                    />
                    <input
                        type="password"
                        name = "password"
                        placeholder = "password"
                        onChange={handleChange}
                        onBlur={handleBlur}
                        value={values.password}
                    />
                    <button type="submit">Submit</button>
                </form>
            )}
        </Formik>
    );
}

Thank you in advance

Answer №1

By default, in the realm of Next.js App Router, pages are considered server components.

The issue arises when a "client"-oriented component is used within a React server component. Formik heavily depends on React hooks (as evidenced by the renderWithHooks call in the backtrace).

Because Server Components do not support React Context, this error occurs.

To resolve this problem, consider adding the following statement at the beginning of your component: "use client";

Read more about React client hook in Server Component here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for enhancing a table with extra functionality in Angular 6

Hi there! I've created a table using Angular 6 and now I'm looking to enhance it with some extra functionality: Implement an overall table search feature Allow users to sort the table by columns Add a "Page x of n" option for pagination I woul ...

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Is there a more effective alternative to using the ternary condition operator for extended periods of time?

Do you know of a more efficient solution to handle a situation like this? <tr [style.background]="level == 'ALARM' ? 'violet' : level == 'ERROR' ? 'orange' : level == 'WARNING' ? 'yellow' ...

Using SCSS variables in TypeScript inside a Vue project

Has anyone had experience with importing SASS (scss) variables into JavaScript in a TypeScript Vue 3 project? // @/assets/styles/colors.scss $white: #fff; // @/assets/styles/_exports.scss @import "./colors.scss"; :export { white: $white; } <templat ...

Encountering difficulty retrieving host component within a directive while working with Angular 12

After upgrading our project from Angular 8 to Angular 12, I've been facing an issue with accessing the host component reference in the directive. Here is the original Angular 8 directive code: export class CardNumberMaskingDirective implements OnInit ...

Transform a list of H1..6 into a hierarchical structure

I have a task to convert H1 to H6 tags from a markdown file into a JavaScript hierarchy for use in a Table of Contents. The current list is generated by AstroJS and follows this format [{depth: 1, text: 'I am a H1'}, {depth: 2: 'I am a H2}] ...

Encountering an error while attempting to set up WebDriverIO with Typescript and Cucumber installation

After completing the project setup, the wdio.conf.ts and tsconfig.json files are saved in a folder named tests. However, the wdio.conf.ts file throws an error on this line: import type { Options } from "@wdio/types"; //located in wdio.conf.t ...

Previewing images with Dropzone through extending file types

Want to display an image preview before uploading using dropzone. Attempting to access the images by calling file.preview but encountering the error "it does not exist on type File." Dropzone extends the file type with a preview?: string. How can I access ...

Is it possible to utilize the inline/hardcoded type declared in the component.d.ts file for reuse

Is there a way to pass props selectively to the library component? The library has hardcoded multiple values in an inline type. If my code needs to automatically update with any new additions to the library-defined type, can I reuse those inline values r ...

Creating or deleting multiple batches of entries in Firebase Realtime Database

I am currently utilizing Firebase real time database in the following way: createSoldLead(soldLead: SoldLeadModel): void { const soldLeadsReference = this.angularFireDatabase.list<SoldLeadModel>( `groups/${this.groupId}/soldLeads` ); ...

Invoking a function from a collection of mixed data types

I have established a mapping for a discriminated union consisting of different types, each linked to a corresponding function that uses a member of the union as a parameter: export interface Truncate { type: 'truncate' maxLength: number } ex ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Using a generic name as a JSON key in a TypeScript file

I received data from an API call const tradingApiResponse = { Timestamp: "2024-01-15T12:00:00", Ack: "Success", Version: 1, Build: "1.0.0", UserDeliveryPreferenceArray: { NotificationEnable: [ { EventType: ...

What could be the reason for receiving an HttpErrorResponse when making a GET request that returns byte data

When using these headers, the API returns byte data as a response. let headers = { headers: new HttpHeaders({ 'Content-Type': 'application/octet-stream', 'responseType':'arraybuffer' as 'js ...

Tips for handling Redux state when a user lands on a product details page without navigating through the application

Currently, I'm tackling a challenge in my Redux application that has left me uncertain about the best approach to take. Imagine I have a page called ProductsList located at example.com/products On this page, I trigger the getProducts redux action wh ...

Could we potentially pause the map and insert a different element into the center instead?

I am currently working on creating a navbar in Nextjs, and I have a specific requirement to include a different element in the middle of the navigation links. {navLinks.map((link, index) => ( <li key={index}> ...

Failed to decipher an ID token from firebase

I'm feeling extremely frustrated and in need of assistance. My goal is to authenticate a user using Google authentication so they can log in or sign up. Everything worked perfectly during development on localhost, but once I hosted my app, it stopped ...

What are the steps to effectively utilize npm warnings within tslint?

After using eslint for javascript files, I am now transitioning to tslint for TypeScript linting. With eslint, I could specify some errors as NPM warnings, such as console logging. https://i.sstatic.net/BNhy6.png I realize that my "warnings" are generat ...

Error: Supabase and Next.js encountered a self-signed certificate within the certificate chain causing an AuthRetryableFetchError

Encountering an error related to certificates while attempting to retrieve the user from Supabase within getServerSideProps using Next.js: AuthRetryableFetchError: request to https://[redacted].supabase.co/auth/v1/user failed, reason: self signed certifica ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...