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:

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

Exciting Dynamic Text Animation in React using styled components

I came across this cool jumping text effect on https://web.dev/patterns/animation/animated-words/ and wanted to incorporate it into my app. However, when I tried implementing the component in React, I encountered some issues. I created a styled component a ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

Troubleshooting a 400 error with the Stripe Webhook due to problems with the raw

After diligently following Stripes documentation on setting up webhooks and testing locally using their Stripe CLI, I have encountered a persistent issue. While I can successfully create events, I consistently receive a response of 400 POST. 2021-12-14 23: ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

Avoiding prop drilling when using server-side rendering in Next.js

How can I prevent prop drilling with SSR in this specific scenario? Layout.tsx: export default function RootLayout({ children, }: { children: React.ReactNode; }) { const user = await getUser(cookies().get("accessToken")?.value); return ...

Creating Multiple Choice Forms in React: A Guide to Implementing Conversational Form

I've been exploring React (Next.js) and I came across an interesting example of how to use multiple choice in simple HTML on Codepen ([https://codepen.io/space10/pen/JMXzGX][1]). Now I'm curious about how to implement a similar functionality in R ...

"Elaborate" Typescript Conditional Generic Types

Scenario I am currently working on implementing strong typing for the onChange function of a UI library's Select component. To provide some context, the existing type definition for their onChange is as follows: onChange?: (...args: any[]) => v ...

Create and save data to a local file using Angular service

I am facing an issue with my Angular service: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { person } from '../interfaces/iperson ...

Obtain the total number of requests submitted by the user within a 24-hour period

I have a POST request point in my API where I need to track and store all work journals made by a worker. export const registerPoint = async (req: Request, res: Response) => { const user = res.locals.decoded; const {id} = user; const point = new Point ...

I am experiencing difficulties with my Angular 8 NPM package as it is unable to locate its own

I am encountering an issue where my assets are successfully copied over to my scoped npm package, but they are not available after the application is served. Currently, the images in my application are searching for a path like this: https://localhost:420 ...

The interface does not allow properties to be assigned as string indexes

Below are the interfaces I am currently working with: export interface Meta { counter: number; limit: number; offset: number; total: number; } export interface Api<T> { [key: string]: T[]; meta: Meta; // encountered an error here } I h ...

Angular 2 forms are displaying ngvalid when input fields are marked as nginvalid

The form displays ngvalid because I have included the code like this: <form novalidate class="pop-form" (submit)="signUp()" #regForm="ngForm"> <div class="group"> <input type="text" [(ngModel)]="signUpData.name" [ngMode ...

Create a function that accepts a class as a parameter and outputs an object of that class

I am working on an instantiator function that generates an instance of a provided class: declare type ClassType = { new (): any }; // known as "ParameterlessConstructor" function createInstance(constructor: ClassType): any { return new constructor(); ...

Discover an alternative to Events by harnessing the power of Observables to effectively listen for dismiss events in Angular Ionic

Currently, I am utilizing Ionic's inline modal feature that is activated by a boolean value. However, after the modal is closed, the boolean does not automatically reset to zero. The Ionic documentation suggests that developers should monitor the ionM ...

The error message states that in order to proceed, "ikm" must specifically be an instance of Uint8Array or a string

I encountered an error while using next.js with typescript, next-auth, prisma, mongodb. The error message reads: TypeError: "ikm"" must be an instance of Uint8Array or a string in vscode Additionally, I received the following two error ...

Instructions for creating a personalized 410 error page using NextJS

I am currently working on managing 410 codes in my nextjs app. While I have already set up a 404 page which is easily handled by nextjs, I am struggling to figure out how to display a custom 410 page. I've attempted to go through the _error page and c ...

TypeScript will show an error message if it attempts to return a value and instead throws an

Here is the function in question: public getObject(obj:IObjectsCommonJSON): ObjectsCommon { const id = obj.id; this.objectCollector.forEach( object => { if(object.getID() === id){ return object; } }); throw new Erro ...

How can we add a key:value pair at a specific position in an array in Angular 2 using Typescript?

Is there a way to insert a key value pair at a specific index in an array? I am currently struggling with this task. Here is the code I have been working on: this.quiz.push( { "question-no":this.no, "Ans":this.ans } I require this functionality to ...

Enhancing collaboration: Seamlessly sharing interface/interface/model files in the integration of

Currently, I am engrossed in developing an application with an Express backend and Typescript whilst utilizing Angular for the frontend. The only snag I'm facing is that I require interface/models files from the backend to be accessible on the fronten ...

Utilizing markModified inside a mongoose class that does not inherit from mongoose.Document

In my Typescript code using mongoose ODM, I am implementing a simple queue structure. The challenge arises when directly mutating an array instead of assigning a new value to it because mongoose doesn't automatically recognize the change. To resolve t ...