#Can I use onClick with a server component?
1 messages · Page 1 of 1 (latest)
Hi @untold nacelle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
No, you cannot use the onClick prop directly with a Server Component in Next.js. Server Components are rendered on the server and do not have access to client-side interactivity like event handlers.
According to the Next.js documentation on Server and Client Component patterns (https://nextjs.org/docs/app/building-your-application/rendering/composition-patterns), Server Components are meant for static content, data fetching, and SEO-friendly elements, while Client Components are used for interactive elements that require state, effects, or browser APIs.
To use onClick or other event handlers, you have two options:
- Convert your component to a Client Component by adding the
'use client'directive at the top of your file:
'use client'
export default function MyComponent() {
return (
<button onClick={() => console.log('Clicked')}>
Click me
</button>
)
}
- Keep your Server Component, but create a separate Client Component for the interactive part:
// Button.tsx (Client Component)
'use client'
export default function Button({ onClick, children }) {
return <button onClick={onClick}>{children}</button>
}
// ServerComponent.tsx (Server Component)
import Button from './Button'
export default function ServerComponent() {
return (
<div>
<h1>Server Component</h1>
<Button onClick={() => console.log('Clicked')}>Click me</Button>
</div>
)
}
This way, you can keep the majority of your component as a Server Component while still having interactive elements handled by Client Components Next.js Client Components (https://nextjs.org/docs/app/building-your-application/rendering/client-components).