#Can I use onClick with a server component?

1 messages · Page 1 of 1 (latest)

untold nacelle
#

I have a component which is not marked as 'use client'. The component has a button. Can I use the onClick prop?

next ospreyBOT
#

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:

  1. 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>
  )
}
  1. 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).

#

Remember, Client Components are rendered on the client-side and can handle interactivity, while Server Components are rendered on the server and cannot directly use client-side features like onClick.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: