I am using NEXTJS and SanityIO. I am getting this error when adding this Framer motion component? "TypeError: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. Read more: https://nextjs.org/docs/messages/context-in-server-component" or it just fails to refresh.
My code causing the problem is below and below the code is a picture of my folder layout. If it is helpful to know, the Header component works if I just render an h1 alone. Any help or feedback is greatly appreciated.
import React from 'react'
import { SocialIcon } from 'react-social-icons';
import {motion} from "framer-motion";
type Props = {}
function Header({}: Props) {
return (
<header className="sticky top-0 p-5 flex items-start justify-between max-w-7xl mx-auto z-
20 xl:items-center">
<motion.div
initial={{
x:-500,
opacity:0,
scale:0.5
}}
animate={{
x:0,
opacity: 1,
scale: 1
}}
transition={{
duration:1.5,
}}
className="flex flex-row items-center">
{/*Social Icons*/}
<SocialIcon
url="https://www.youtube.com"
fgColor="gray"
bgColor="transparent"
/>
<SocialIcon
url="https://www.youtube.com"
fgColor="gray"
bgColor="transparent"
/>
<SocialIcon
url="https://www.youtube.com"
fgColor="gray"
bgColor="transparent"
/>
</motion.div>
<motion.div
initial={{
x: 500,
opacity: 0,
scale: 0.5,
}}
animate={{
x:0,
opacity:1,
scale:1,
}}
transition={{duration:1.5}}
className="flex flex-row items-center text-gray-300 cursor-pointer">
<SocialIcon
className="cursor-pointer"
network="email"
fgColor="gray"
bgColor="transparent"
/>
<p className="uppercase hidden md:inline-flex text-sm text-gray-400"> Get In Touch</p>
</motion.div>
</header>
)
}
export default Header
2
Answers
I got the same problems when using Framer Motion. I think this problem is becoming from the new AppDir of Next.js 13. I read the beta documents here: https://beta.nextjs.org/docs/rendering/server-and-client-components
For fixing this issues, I added
'use client';
in the first line before import libraries.As Phong and the error msg are saying, just adding the "use client" directive at the very top of the file will fix the issue.
By default, Next13 (React18) is introducing a server-side component, which means the component is rendered on the server and shipped to the client
and
the general rule of thumb is that if you are using third-party libraries or you are using hooks, or some interactivity ( e.g. onClick ) – you need to set this "use client" directive.
Basically, if it’s possible to make a server component, I’d consider doing it over the client side because less code will be shipped to the client.